使用 jQuery 进行同步 ajax 调用的非弃用方法是什么?

Fas*_*him 6 javascript ajax jquery

我有一个小的 javascript 函数,它的唯一目的是调用脚本从数据库中获取一些数据,以便客户端的其他函数可以使用它。

我正在使用 jQuery 调用来获取数据,但是为了将对象传递出成功函数范围,我需要关闭异步,这会引发弃用警告。

我的函数目前按预期工作,但我想使用一种未被弃用的方法。这是我的功能:

function getData(ID) {
  var Data = {};
  $.ajax({
    url: 'script',
    method: 'POST',
    dataType: 'json',
    async: false,
    data: {action: 'get', id: ID },
    success: function(response) {
      Data = response;
    })
  });
  return Data;
}
Run Code Online (Sandbox Code Playgroud)

出于隐私原因,我更改了变量名称,如果它们含糊不清,请见谅。

还有为什么同步调用被认为对最终用户体验有害?

Par*_*xit 5

由于 AJAX 调用asynchronous,您将始终得到空白对象({} ) 作为响应。

有2种方法。

  1. 你可以做async:false
  2. 要获取 AJAX 调用中返回的响应,请尝试如下代码。等待服务器的响应。

function getData(ID) {
  return $.ajax({
    url: 'script',
    method: 'POST',
    dataType: 'json',
    //async: true,  //default async call
    data: {action: 'get', id: ID },
    success: function(response) {
         //Data = response;
    })
  });
}


$.when(getData(YOUR_ID)).done(function(response){
    //access response data here
});
Run Code Online (Sandbox Code Playgroud)

  • 如果设置了“async: false”,为什么还要使用“$.when”? (2认同)