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

时间:2022-10-07 14:41:42

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上,为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().

从jQuery 1.8开始,不推荐使用async:false和jqXHR($ .Deferred);必须使用success / error / complete回调选项,而不是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; 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!

非常感谢!

1 个解决方案

#1


-1  

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;
};

#1


-1  

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;
};