我正在使用@ Phrogz's quick script使用以下命令取消除最后一个 AJAX 请求之外的所有请求:
var fooXHR, fooCounter=0;
$('div').bind( 'click', function(){
// Do the Right Thing to indicate that we don't care about the request anymore
if (fooXHR) fooXHR.abort();
var token = ++fooCounter;
fooXHR = $.get( ..., function(data){
// Even aborted XHR may cause the callback to be invoked
if (token != fooCounter) return;
// At this point we know that we're using the data from the latest request
});
});
这个脚本工作得很好,但是如果我在页面加载时一次加载 3 个 div
并期望加载所有 3 个的结果,上面的脚本将只显示最后一个(因为前两个根据上面的脚本中止)。
你能给我指明正确的方向,通过包含的 DOM 元素来限制上述脚本吗?
例如……
<div id="one">1. run ajax on pageload and on click</div>
<div id="two">2. run ajax on pageload and on click</div>
<div id="three">3. run ajax on pageload and on click</div>
我希望所有三个 div 在页面加载或单击时返回 ajax 请求。我想保留点击取消之前的 AJAX 请求的功能。但是,我不想点击 div#one
来取消从 div#two
调用的 ajax 请求。
你关注吗?
最佳答案
只需使用散列来存储每个 div
的 xhr 和计数器变量:
var requests = {};
$('div').bind( 'click', function(){
var div = this;
// init the entry for the div
if (requests[div] === undefined) {
requests[div] = {};
requests[div].counter = 0;
}
// abort the old request
if (requests[div].xhr !== undefined) {
requests[div].xhr.abort();
}
var token = ++requests[div].counter;
request[div].xhr = $.get( ..., function(data) {
// check for correct request
if (token !== requests[div].counter) return;
// ...
});
});
关于javascript - 如何按对象限制 Javascript 计数器变量的范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16685467/