jQuery的AJAX同步调用beforeSend [英] jquery ajax synchronous call beforeSend

查看:766
本文介绍了jQuery的AJAX同步调用beforeSend的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个调用的函数:

function callAjax(url, data) {
 $.ajax(
   {
     url: url, // same domain
     data: data,
     cache: false,
     async: false, // use sync results
     beforeSend: function() {
       // show loading indicator
     },
     success: function() {
       // remove loading indicator 
     }
   }
  );
}

在code,我打电话的时候callAjaxX号,我想同步更新数据。它是作为预期,但一个问题:加载项中不beforeSend功能显示。如果我把异步为真,它的工作原理,但更新不同步完成。

In the code, I call "callAjax" X number of times and I want to update the data synchronously. It is done as expected, but one problem: the loading item doesn't show in beforeSend function. If I turn async to true, it works but the updates aren't synchronously done.

我已经试过几件事情没有成功。我试图把负载指示这样的AJAX调用之前:

I've tried several things with no success. I tried putting the loading indicator before the ajax call like this:

function callAjax(url, data) {
  // show loading div

  $.ajax(
    {
      // same as above
    }
   );
}

但由于某些原因,它不希望显示加载指示器。我注意到一个奇怪的现象,当我把在beforeSend一个警告和装载指示出现在这种情况下,但我宁可不要一个消息框弹出。

But for some reason it doesn't want to show the loading indicator. I notice a strange behavior when I put an "alert" in the beforeSend and the loading indicator appears in that case, but I rather not pop up a message box.

有什么想法?

推荐答案

制作这样的同步调用就像是搭一个警报()复选框。有些浏览器停止他们在做什么,完全,直到接收HTTP响应。

Making a synchronous call like that is like putting up an "alert()" box. Some browsers stop what they're doing, completely, until the HTTP response is received.

因此​​,你调用$。阿贾克斯()函数开始在code,之后,什么反应,直到接收到响应,接下来的事情,只要你的$ C $Ç云将是成功的处理程序。

Thus in your code, after your call to the "$.ajax()" function begins, nothing happens until the response is received, and the next thing as far as your code goes will be the "success" handler.

一般情况下,除非你的真正的信心,你的服务器,这是一个更好的主意,用异步调用。当你这样做的,浏览器立即返回到它的工作,只是听在后台的HTTP响应。当响应到达时,你的成功处理程序将被调用。

Generally, unless you're really confident in your server, it's a much better idea to use asynchronous calls. When you do it that way, the browser immediately returns to its work and simply listens in the background for the HTTP response. When the response arrives, your success handler will be invoked.

这篇关于jQuery的AJAX同步调用beforeSend的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆