javascript - 取消ajax请求: can the handler still be executed

标签 javascript jquery ajax jquery-deferred request-cancelling

Is JavaScript guaranteed to be single-threaded? 很明显,尽管 javascript 是单线程的,但仍然存在一些警告。

我想知道以下伪代码是否总是可预测的(我“使用”jQuery)

var lastReq;
$('#button').click(function()
{
  if (lastReq) lastReq.abort();
  lastReq = $.ajax(...);
});

这种情况可能是在单击事件和中止之间,来自服务器的数据通过并将事件放入事件队列中。如果这种情况发生在中止之前,则会触发 ajax post 的 succes 事件。 我不知道如何真正测试这种可能的竞争条件。

有人知道这是如何工作的吗?或者如何使用准备好的示例来测试它?

最佳答案

我不知道这个解决方法是否真的有用并且防弹(我正在努力发挥创意),但是,由于 jQuery 1.5 ajax 方法返回一个延迟对象 lastReqstate() 方法可用

来自http://api.jquery.com/deferred.state/

The deferred.state() method returns a string representing the current state of the Deferred object. The Deferred object can be in one of three states:

...

"resolved": The Deferred object is in the resolved state, meaning that either deferred.resolve() or deferred.resolveWith() has been called for the object and the doneCallbacks have been called (or are in the process of being called).

这样你就可以像这样重构你的代码

var lastReq;
$('#button').click(function() {
     if (lastReq) {
         if (lastReq.state() === "resolved") {
             return false; /* done() of the previous ajax call is in the process of
                              being called. Do nothing and wait until the state 
                              is resolved */
         }
         else {
             lastReq.abort(); 
         }
     }

     lastReq = $.ajax(url).done(function() {
          /* do something */
          lastReq = null; 
     });
});

希望这可以帮助您提供一个可行的想法,但我怀疑实际上并不需要这种解决方法

关于javascript - 取消ajax请求: can the handler still be executed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10249591/

相关文章:

javascript - 在不重新创建标记的情况下测试 JavaScript 代码?

javascript - 从不同域中的 frame/iframe 获取顶部窗口 url

jquery - 使用JQuery的验证插件好不好?

javascript - 在不刷新页面的情况下打开更改DIV

javascript - 邮寄到 : anchor links unloading html5 video in Chrome

javascript - 如何给金额字段占位符 00.00 ,该占位符会随着我们输入数字而改变

javascript - 使用 AJAX 从 JavaScript 调用 PHP 函数

php - jQuery ajax 在每个函数中发布,每个函数都成功继续

javascript - 如何在 id 列表上使用 jquery 事件?

javascript - 当我尝试打开文件并写入时出现问题