简体   繁体   English

循环中的XMLHttpRequest

[英]XMLHttpRequest in For-Loop

This code is supposed to loop through several webpages and find all the links on each page, listing them in console as it goes, but it seems to be listing only links from the very last webpage (fakeURL.com/735). 该代码应该在多个网页中循环并找到每个页面上的所有链接,并在控制台中将其列出,但似乎仅列出最后一个网页(fakeURL.com/735)中的链接。

How I can get console.log(url); 我如何获得console.log(url); to work for every iteration, instead of just the last one (which is when i=735)? 可以为每一次迭代工作,而不仅仅是最后一次迭代(当i = 735时)?

for(i = 0; i <= 735; i += 15) 
{
    var xhrs = new XMLHttpRequest();
    xhrs.open("get", 'http://fakeURL.com/' + i, true);
    xhrs.onreadystatechange = function() 
    {
        if (xhrs.readyState == 4) 
        {
            $(xhrs.responseText).find('a').each(function()
            {           
                var url = $(this).attr('href');
                console.log(url);                                               
            });
        }
    }
        xhrs.send();
}

Your issue is that you're reusing the same xhrs variable for all your ajax calls. 您的问题是您对所有的ajax调用都使用了相同的xhrs变量。 Thus all the calls in play at once can't find the xhrs variable that belongs to their specific request when the onreadystatechange event fires. 因此,当onreadystatechange事件触发时,所有xhrs的调用都无法立即找到属于其特定请求的xhrs变量。 Thus, they all end up looking at the xhrs.readyState from the last request so you only ever see the last request complete. 因此,它们最终都会查看来自最后一个请求的xhrs.readyState ,因此您只会看到最后一个请求已完成。

You should be able to switch to using this to refer to the request who generated the onreadystatechange event: 您应该能够切换到使用this来引用生成onreadystatechange事件的请求:

for(i = 0; i <= 735; i += 15) {
    var xhrs = new XMLHttpRequest();
    xhrs.open("get", 'http://fakeURL.com/' + i, true);
    xhrs.onreadystatechange = function() 
    {
        if (this.readyState == 4) 
        {
            $(this.responseText).find('a').each(function()
            {           
                var url = $(this).attr('href');
                console.log(url);                                               
            });
        }
    }
    xhrs.send();
}

As others have said, if $ indicates that you're using jQuery, then jQuery.ajax() would likely be a lot easier. 正如其他人所说,如果$表示您正在使用jQuery,则jQuery.ajax()可能会容易jQuery.ajax()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM