简体   繁体   中英

How/Whether to rewrite async:false AJAX function?

I'm using an AJAX call with async:false to return data, like this:

var my_data = my_function(10, 20);

function my_function(value1, value2) {
    var returnData;
    $.ajax({
      type: 'POST',
      url: 'my_function.php',
      data: { variable1: value1, variable2: value2 },
      success: function(data) { returnData = data; },
      async:false
    });
    return returnData;
};

Notice that I've set async:false , which is necessary in the context of my code, and works perfectly.

Howverer, at the JQuery API, this message is provided for the entry on async:

As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success().

I'm having trouble making sense of that warning as regards my function, as I'm not using $.Deferred in my routine; the warning still may apply in a way I don't appreciate. So, is it safe to leave the code as-is, or should it be rewritten in light of the deprecation of async , and if so, how should it be rewritten? (I need the function performed synchronously.)

Many thanks!

The code you provided looks good. The following is a version that is being deprecated (don't do this):

var my_data = my_function(10, 20);

function my_function(value1, value2) {
    var returnData;
    $.ajax({
      type: 'POST',
      url: 'my_function.php',
      data: { variable1: value1, variable2: value2 },
      async:false
    }).success(function(data) { returnData = data; });
   return returnData;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM