循环内的 jQuery.ajax() [英] jQuery.ajax() inside a loop

查看:19
本文介绍了循环内的 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/

这篇关于循环内的 jQuery.ajax()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆