循环内的 jQuery.ajax()
如果我在循环中调用 jQuery.ajax()
,是否会导致当前迭代中的调用覆盖上次调用或为新请求分配新的 XHR 对象?
If I call jQuery.ajax()
inside a loop, would it cause the call in current iteration overwrite the last call or a new XHR object is assigned for the new request?
我有一个循环来执行此操作,而从控制台日志中我可以看到请求已完成 200 ok
但只有循环中最后一个请求的结果数据由请求 success 存储回调
.
I have a loop that do this, while from console log I can see requests done 200 ok
but just the result data of the last request in the loop is stored by the request success callback
as supposed .
代码:
var Ajax = {
pages: {},
current_request: null,
prefetch: function () {
currentPath = location.pathname.substr(1);
if(this.pages[currentPath])
{
var current = this.pages[currentPath];
delete this.pages[currentPath];
current['name']=currentPath;
current['title']=$("title").text().replace(' - '.SITE_NAME, '');
current['meta_description']=$("meta[name=description]").attr('content');
current['meta_keywords']=$("meta[name=keywords]").attr('content');
}
var _Ajax = this;
//the loop in question *****
for(var key in this.pages)
{
$.ajax({
method: 'get',
url:'http://'+location.hostname+'/'+key,
success: function(data) {
_Ajax.pages[key] = data;
}
});
console.debug(this.pages);
}
if(current)
{
this.pages[currentPath] = current;
}
}
};//Ajax Obj
for(var i in pages)
{
Ajax.pages[pages[i]]={};
}
$(function() {
Ajax.prefetch();
});//doc ready
推荐答案
你需要一个 key
的闭包:
You'll need a closure for key
:
for(var k in this.pages){
(function(key){
$.ajax({
method: 'get',
url:'http://'+location.hostname+'/'+key,
success: function(data) {
_Ajax.pages[key] = data;
}
});
console.debug(this.pages);
})(k);
}
这样您就可以确保在每个 ajax 成功回调中该键始终是正确的.但除此之外它应该可以工作
that way you make sure that key is always the correct on in each ajax success callback. but other than that it should work
我用超时代替ajax做了一个小闭包演示,但原理是一样的:
i made a small closure demonstration using timeout instead of ajax but the principle is the same:
http://jsfiddle.net/KS6q5/
相关文章