Warm tip: This article is reproduced from serverfault.com, please click

其他-用于循环的Javascript仅给出一个输出

(其他 - Javascript for loop only giving one output)

发布于 2020-11-27 23:39:44

我一直在玩这个东西太久了...

function OnSearch() {
    var text_in = sVal()
    var tArea = document.getElementById("SearchResults")
    var loadstr = "Loading results for "
    var xhttp = new XMLHttpRequest();
    var altStr = ""
    var sendstr = ""
    var urls = []
    for (i = 0; i < ciphersOn.length; i++) {
        aCipher = ciphersOn[i]
        sendstr += "/search="+text_in+""
        sendstr += '/name=' + aCipher.Nickname + ''
        sendstr += '/letters='

        for (x = 0; x < aCipher.cArr.length; x++) {
            sendstr += String.fromCharCode(aCipher.cArr[x])
        }
        sendstr += "/cipher="
        for (x = 0; x < aCipher.vArr.length; x++) {
            if(aCipher.vArr.length == x+1){
                sendstr += aCipher.vArr[x]
            } else sendstr += aCipher.vArr[x] + "-"

           }
        /* send http GET and bring back info to a new list, then clear sendstr before it loops again. */

        urls.push(sendstr)
        sendstr=""

    }
    for(i = 0; i < urls.length; i++) {
        xhttp.open("GET", "http://localhost:8000" + urls[i] + "", true);
        xhttp.send();

    }

    loadstr += '"' + text_in + '"' + sendstr + '' + urls.length + '' + aURL + '' /* the purpose of this is so I can see what is happening to my code */
    tArea.innerHTML = loadstr

}

我不知道为什么最后的for循环只发送一个GET请求。拜托,请让我保持理智……我就是不明白。数组“ urls”包含我需要的信息,并且变量“ sendstr”运行得很好...为什么然后我的终端仅显示给出的第一个结果?

Questioner
John Wilkes Booth
Viewed
22
Aplet123 2020-11-28 07:43:23

每个人XMLHttpRequest只能发送一个请求。如MDN中所述,调用open已经打开的请求等同于中止该请求。因此,XMLHttpRequest为每个循环创建一个新的:

for(i = 0; i < urls.length; i++) {
    var xhttp = new XMLHttpRequest();
    xhttp.open("GET", "http://localhost:8000" + urls[i], true);
    xhttp.send();
}

或者,迁移到fetch

for(i = 0; i < urls.length; i++) {
    fetch("http://localhost:8000" + urls[i]);
}