How to use multiple XMLHttpRequest?

后端 未结 3 916
青春惊慌失措
青春惊慌失措 2021-02-02 01:08

I need to get 8 JSON from 8 different URL. I stored the query string that I have to change in an Array and I loop through it with a for loop. Here is my code:

va         


        
3条回答
  •  你的背包
    2021-02-02 01:26

    The problem is that you declare

    var request = new XMLHttpRequest();
    

    outside of the for loop. So you instance only one request.

    You have to include it inside the for loop.

    Also, don't forget that ajax is executed asynchronous so you will get the results in a random order.

    The value of i variable must be declared using let keyword in order to declare a block scope local variable.

    let allows you to declare variables that are limited in scope to the block.

    let is always used as a solution for closures.

    Also, you can use an array where you can store the XMLHttpRequest.

    var index = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
    requests=new Array(index.length);
    for (let i = 0; i < index.length; i++) {
        var url = "https://wind-bow.glitch.me/twitch-api/channels/" + index[i];
        requests[i] = new XMLHttpRequest();
        requests[i].open("GET", url);
        requests[i].onload = function() {
            var data = JSON.parse(requests[i].responseText);
            console.log(data);
        }
        requests[i].send();
    }

提交回复
热议问题