ForH循环中的XMLHttpRequest DOMparser仅返回最后一次迭代

时间:2014-10-05 18:01:19

标签: javascript jquery for-loop domparser

下面的代码应该遍历几个网页,每个网页都由i的值确定,console.log(url);行应列出这些网页中的每个网址。相反,代码仅在“i”处于最后一次迭代(i = 0)时列出URL,因此它仅从它请求的最终网页(http://fakeURL.com/0)中检索URL - URL末尾的数字代表“我”。

如何从所有迭代(当i = 45,30,15和0)而不是仅最后一次迭代(当i = 0时)制作控制台列表URL?

for(i = 45; i >= 0; i -= 15) 
{
    var xhrs = new XMLHttpRequest();                                    
    xhrs.open("get", 'http://fakeURL.com/' + i, true);
    xhrs.onload = function()
    {       
            var doc2 = xhrs.response;
            $(doc2).find('a').each(function()
            {   

                var url = $(this).attr('href');
                console.log(url);

            });

    }
    xhrs.responseType = 'document';
    xhrs.send();
}

编辑:在做了Teemu建议之后,下面是我的实际源代码(未简化)。现在,对于for循环使用XMLHttpRequest的每个请求,'i'总是-15:

var url;
var title;
function ajaxCall (x, y)
{
    setTimeout(function ()
    {
        var xhrs = new XMLHttpRequest();                                    
        xhrs.open("get", 'http://fakeURL.com/' + i, true);
        xhrs.onload = function()
        {       
            var doc2 = xhrs.response;
            $(doc2).find('a').each(function()
            {                                           
                var x = $(this).attr('href');
                var y = $(this).text();

                console.log(x);
                console.log(y);
            });

        }
        xhrs.responseType = 'document';
        xhrs.send();
    }, Math.random() * 1000 + 1000);
}

for(i = 45; i >= 0; i -= 15) 
{   
    ajaxCall(url, title);
}

知道为什么'我'总是-15?

编辑2:我没有在上面的代码中正确地遵循Teemu的解决方案。以下是未来参考的固定版本:

var i;
function ajaxCall (x)
{
        var xhrs = new XMLHttpRequest();                                    
        xhrs.open("get", 'http://fakeURL.com/' + x, true);
        xhrs.onload = function()
        {       
            var doc2 = xhrs.response;
            $(doc2).find('a').each(function()
            {                                           
                var url = $(this).attr('href');
                var title = $(this).text();

                console.log(url);
                console.log(title);
            });

        }
        xhrs.responseType = 'document';
        xhrs.send();
}

for(i = 45; i >= 0; i -= 15) 
{   
    ajaxCall(i);
}

0 个答案:

没有答案