简体   繁体   English

如何/是否重写async:false AJAX函数?

[英]How/Whether to rewrite async:false AJAX function?

I'm using an AJAX call with async:false to return data, like this: 我正在使用带有async:false的AJAX调用来返回数据,如下所示:

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. 注意,我已经设置了async:false ,这在我的代码上下文中是必需的,并且可以完美地工作。

Howverer, at the JQuery API, this message is provided for the entry on async: 但是,在JQuery API上,此消息是为异步项提供的:

As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; 从jQuery 1.8开始,不建议使用async:false和jqXHR($ .Deferred); 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(). 您必须使用成功/错误/完成回调选项,而不要使用jqXHR对象的相应方法,例如jqXHR.done()或已弃用的jqXHR.success()。

I'm having trouble making sense of that warning as regards my function, as I'm not using $.Deferred in my routine; 我在理解有关我的功能的警告时遇到了麻烦,因为我没有在例程中使用$.Deferred 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? 因此,将代码保持原样是安全的,还是应该根据不赞成使用async进行重写,如果是,则应如何重写? (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;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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