問題描述
如果我在循環(huán)中調(diào)用 jQuery.ajax()
,是否會(huì)導(dǎo)致當(dāng)前迭代中的調(diào)用覆蓋上次調(diào)用或?yàn)樾抡?qǐng)求分配新的 XHR 對(duì)象?
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?
我有一個(gè)循環(huán)來(lái)執(zhí)行此操作,而從控制臺(tái)日志中我可以看到請(qǐng)求已完成 200 ok
但只有循環(huán)中最后一個(gè)請(qǐng)求的結(jié)果數(shù)據(jù)由請(qǐng)求 success 存儲(chǔ)回調(diào)
.
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
推薦答案
你需要一個(gè) 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);
}
這樣您就可以確保在每個(gè) ajax 成功回調(diào)中該鍵始終是正確的.但除此之外它應(yīng)該可以工作
that way you make sure that key is always the correct on in each ajax success callback. but other than that it should work
我用超時(shí)代替ajax做了一個(gè)小閉包演示,但原理是一樣的:
i made a small closure demonstration using timeout instead of ajax but the principle is the same:
http://jsfiddle.net/KS6q5/
這篇關(guān)于循環(huán)內(nèi)的 jQuery.ajax()的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!