WebApi 2 中的同步 XMLHttpRequest

Synchronous XMLHttpRequest in WebApi 2

我有一个 webApi 2 应用程序。我以这种方式多次使用 Ajax async:false ,因为有时

The statement I am calling has to be complete before the next statement in my function can be called

然后我收到浏览器警告

主线程上的同步 XMLHttpRequest 已弃用,因为它会对最终用户的体验产生不利影响。

我知道同步调用 Web 服务会导致长时间等待、浏览器崩溃等问题。但我需要在继续下一条语句之前获取结果。

我需要知道

  1. 如何避免此警告并使调用异步?
  2. 为什么Synchronous XMLHttpRequest on the main thread is deprecated?这句话是什么意思?

您可以将同步调用移至网络工作者。但同样,你会做到 async.

最好将当前对服务器的同步调用作为异步调用。

示例(伪同步调用代码):

var dataFromServer = makeSyncCallToServer();
//use dataFromServer

示例(伪异步调用代码):

makeAsyncCallToServer(function(dataFromServer) {
  //use dataFromServer here
});

如果你想对服务器进行多次调用,那么async在这里就派上用场了。

例如,您可以使用 async.series

async.series([yourAsnycFunctionOne, yourAsnycFunctionTwo, yourAsnycFunctionThree], finalFunctionToCall)

所以yourAsnycFunctionOne, yourAsnycFunctionTwo, yourAsnycFunctionThree会串联调用,finalFunctionToCall会在系列结束时调用

对于你的情况,你可以这样做:

function getCustomerList(callback) {
   //make the async http call and call "callback" with the customer data
}
function postFormDataToServer(formdata, callback) {
  //send form data server and call "callback" after successful post
}
function hideGrid() {}
function hideForm() {}
function showForm() {}
function showGrid() {}
$('#add-button').on('click', function() {
  showForm();
  hideGrid();
});
$('#form-id').on('submit', function(e) {
  e.preventDefault();
  var formdata = {/**populate form data**/};
  hideForm();
  postFormDataToServer(formdata, function() {
    getCustomerList(function(customerList) {
      //populate grid with new data
      showGrid();
    });
  });
});