如果我打电话jQuery.ajax()
在循环内,是否会导致当前迭代中的调用覆盖上次调用或为新请求分配新的 XHR 对象?
我有一个循环可以执行此操作,而从控制台日志中我可以看到已完成的请求 200 ok
但请求 success callback
仅存储循环中最后一个请求的结果数据正如所料。
代码:
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
的闭包:
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 成功回调中的 key 始终是正确的。 但除此之外它应该可以工作
我用timeout代替ajax做了一个小的闭包演示,但原理是一样的:
关于ajax - 循环内的 jQuery.ajax(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17981631/