【问题标题】:Chrome Extension - XHR URLs from an arrayChrome 扩展 - 来自数组的 XHR URL
【发布时间】:2011-05-25 14:46:25
【问题描述】:

我已将一些主题 URL 密钥保存到 localStorage,现在想循环访问它们以获取每个主题的内容。

// Walk through saved subjects
allSubjects = JSON.parse(localStorage.getItem('subjects'));
var i = 0;
var ii = 0;

var xhrIn = [];
for (i = 0; i < allSubjects.length; i++) {
    xhrIn[i] = new XMLHttpRequest();
    xhrIn[i].open("GET", "https://myserver.com/" + allSubjects[i], true);
        xhrIn[i].onreadystatechange = function() {
            if (xhrIn[ii].readyState == 4) {
                console.log(xhrIn[ii].responseText);

                percents = Math.floor((((ii+1)/allSubjects.length)*100));
                $("div#status").text('Downloading... ' + percents + '%');

                // Final phase
                if ((ii+1) == allSubjects.length) {
                    $("div#status").text("All downloaded and saved in console.");
                }
                ii++;
            }
        };
        xhrIn[i].send();
    }
}

这不起作用,它只捕获第一个 URL,之后我的控制台日志显示所有其他 URL 都已联系,但从未执行 xhrIn[i].onreadystatechange 闭包。

这对我来说似乎有点神奇……谁能解释一下这种行为?

【问题讨论】:

  • 订单不保证,所以里面的东西是错误的。

标签: javascript google-chrome-extension lifecycle xmlhttprequest


【解决方案1】:

是的,我同意 epascarello 的观点,这段代码存在一些基本问题。不能保证分配的回调按照您想要的顺序运行。如果您希望它们按顺序运行,请尝试以下操作:

var urls = ['test.php', 'test2.php', test3.php'];// and so on

function myRequest(){
    if(urls.length > 0){
        var nextUrl = urls.pop(); //TAKE THE NEXT URL (pop() removed from the end)
        var xhrIn = new XMLHttpRequest();
        xhrIn.open("GET", "https://myserver.com/" + nextUrl, true);
        xhrIn.onreadystatechange = function() {
            if (xhrIn.readyState == 4) {
                console.log(xhrIn.responseText);
                //THE FOLLOWING LINE WILL OBVIOUSLY NOT WORK ANY MORE
                //percents = Math.floor((((ii+1)/urls.length)*100));
                //$("div#status").text('Downloading... ' + percents + '%');
                myRequest(); //RECUR WHEN DONE WITH PREVIOUS REQUEST
            }
        }

    }
}

【讨论】:

  • 百分比计数可以通过将变量 i 作为 myRequest 参数在每次迭代中传递来完成。 ;-)
【解决方案2】:

没有测试过,应该是这样的:

for (i = 0; i < allSubjects.length; i++) {
    xhrIn[i] = new XMLHttpRequest();
    xhrIn[i].open("GET", "https://myserver.com/" + allSubjects[i], true);

    xhrIn[i].onreadystatechange = (function(ii) {
        return function() {
            if (xhrIn[ii].readyState == 4) {
                console.log(xhrIn[ii].responseText);
            }
        };
    })(i);

    xhrIn[i].send();

}

您当前的百分比计算会到处乱跳,因为回调函数可以按随机顺序调用。您可能需要重新考虑该部分(创建一些全局计数器)。

【讨论】:

    猜你喜欢
    • 2012-07-02
    • 1970-01-01
    • 2012-11-25
    • 1970-01-01
    • 2015-06-09
    • 2012-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多