Wait for jQuery $.get function to finish before running code

前端 未结 3 1661
伪装坚强ぢ
伪装坚强ぢ 2020-12-19 23:12

In the following, the return statement is being executed before the call to $.get() finishes. How can I change this?



        
相关标签:
3条回答
  • 2020-12-19 23:56

    jQuery supports this out of the box, set the option async to false and the function call will be synchronous, instead of asynchronous.

    Though I'd recommend you to keep the request async, see the "recommended solution" at the end of this post.

    • jQuery.ajax() – jQuery API

    async (Boolean) Default: true

    By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation.

    Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.


    But I'm using $.get, that seems to be specific for $.ajax?

    Yes, but under the hood they are exactly the same thing.

    jQuery.get ():

    This is a shorthand Ajax function, which is equivalent to:

    $.ajax({
      url: url,
      data: data,
      success: success,
      dataType: dataType
    });
    

    Sample implementation

    aft.getToken = function (url) {
      var theToken;
    
      $.ajax({
        url: url,
        dataType: 'html'
        success: function (data) {
          theToken = $(data).find('input[name=__RequestVerificationToken]').val();
        },
        dataType: dataType
      });
    
      return theToken;
    }
    

    Recommended solution

    As stated by the previously mentioned comment from the jQuery documentation asynchronous requests are normally NOT recommended, and will most often to more harm than good.

    Instead you should try to implement the functionality asked for by using a callback or similar.

    A callback is a function passed to some other function to handle a certain event, such as the success of your data retrieval. Just as you are passing a callback to $.get in your own snippet.

    Make your function aft.getToken accept a second parameter named callback which should be a function reference. Then call this function with the token replied by your ajax request as a parameter when data retrieval and "parsing" is finished.

    aft.getToken = function (url, callback) {
      var dst_object = this;
    
      $.get (url, function (data) {
        dst_object.stored_token = $(data).find (
          'input[name=__RequestVerificationToken]'
        ).val ();
    
        callback (dst_object.stored_token);
      }, "html");
    };
    
    ...
    
    aft.getToken ('/path/to/file.html', function (token) {
      console.log ("Got token: " + token);
    });
    
    ...
    
    console.log (aft.stored_token);
    
    0 讨论(0)
  • 2020-12-20 00:05

    You can't—at least not sensibly. While there is an async property you can set on jQuery ajax requests, I've had serious problems trying to use it with a false value in the past.

    Try to re-think what you're trying to accomplish:

    var aft = { yourToken: '' };
    
    aft.setToken = function (url, callback) {
        $.get(url, function (data) {
            this.yourToken = $(data).find('input[name=__RequestVerificationToken]').val();
    
            if (callback)
               callback.apply(this);
        }, "html");
    };
    

    And then:

    aft.setToken("url.php", function() {
       alert("Token retrieved = " + this.yourToken);
    });
    

    Or, if your callback only needs access to the returned data, then you could more simply do

    if (callback)
        callback(data);
    

    And then

    aft.setToken("url.php", function(dataReturned) {
       alert("Ajax data retrieved = " + dataReturned);
    });
    
    0 讨论(0)
  • 2020-12-20 00:10

    The callback code by @Adam Rackis is working for me. In fact, if the content of the url is of json structure, you can directly refer the fields like this. Note that aft = { yourToken :'' } is just dummy since I am not using the value in this dictionary at all. I just want to get the user_id from the URL.

    var aft = { yourToken: '' };
        aft.setToken = function(url, callback){
            $.get(url, function(data) {
                user_id = data[0]['user_id'];
                if (callback)
                    callback(data);
            });
        };
    
        aft.setToken("https://XXXXXX.azurewebsites.net/.auth/me",  function(dataReturned){
            alert("You user id is " + labeler);
    
    0 讨论(0)
提交回复
热议问题