jQuery.ajax()在循环中 [英] jQuery.ajax() inside a loop
问题描述
如果我称之为 jQuery.ajax()
在循环中,这会导致当前迭代的通话覆盖的最后一个电话或一个新的XHR对象被分配给新要求?
我有一个循环,做到这一点,而从控制台日志,我可以看到做请求 200 OK
,但在循环的最后一个请求的只是结果数据被存储请求成功回调
像预想的那样。
在code:
VAR阿贾克斯= {
网页:{},
current_request:空,
prefetch:函数(){
currentPath = location.pathname.substr(1);
如果(this.pages [currentPath])
{
无功电流= this.pages [currentPath]
删除this.pages [currentPath]
当前['名称'] = currentPath;
电流['标题'] = $(标题)文本()代替( - .SITE_NAME,'')。。
当前['meta_description'] = $(元[名称=说明])ATTR(内容)。
当前['meta_keywords'] = $(元[名称=关键字])ATTR(内容)。
}
VAR _Ajax =这一点;
//有问题的循环*****
为(在this.pages VAR键)
{
$阿贾克斯({
方法:'得到',
网址:HTTP://'+location.hostname+'/'+key,
成功:功能(数据){
_Ajax.pages [关键] =数据;
}
});
console.debug(this.pages);
}
如果(当前)
{
this.pages [currentPath] =电流;
}
}
}; //的Ajax的OBJ
为(在页面变种I)
{
Ajax.pages [页[I] = {};
}
$(函数(){
阿贾克斯prefetch()。
}); //文档就绪
您将需要一个封闭的键
:
的(在this.pages变种K){
(函数(键){
$阿贾克斯({
方法:'得到',
网址:HTTP://'+location.hostname+'/'+key,
成功:功能(数据){
_Ajax.pages [关键] =数据;
}
});
console.debug(this.pages);
})(k)的;
}
这样,你要确保关键的是始终在每个阿贾克斯成功回调正确的。 但除此之外,它应该工作
我做了使用超时,而不是AJAX的小封闭的示范,但原理是一样的:
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?
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 .
the code:
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
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);
}
that way you make sure that key is always the correct on in each ajax success callback. but other than that it should work
i made a small closure demonstration using timeout instead of ajax but the principle is the same:
这篇关于jQuery.ajax()在循环中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!