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

Javascript for loop only giving one output

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

I've been toying with this for far too long...

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

}

I have no clue why that for loop at the end only sends one GET request. Please, spare me my sanity... I just don't get it. The array "urls" contains the information I need, and the variable "sendstr" works perfectly well... Why then does my terminal only show that the first result is being given?

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

Each XMLHttpRequest can only send one request. As stated in MDN, calling open on an already open request is equivalent to aborting the request. So, create a new XMLHttpRequest for each loop:

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

Alternatively, migrate to fetch:

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