How to handle Simultaneous javascript xmlhttprequests? [duplicate]

老子叫甜甜 提交于 2019-11-28 08:48:29

The problem (ignoring the cross-domain issue that slebetman covered) is that when your ready state change callback is fired it is using the i variable from the containing scope which will be 3 after the loop completes. One way to fix that is as follows:

for (var i=0; i<3; i++){
   (function(i) {
      nRequest[i] = new XMLHttpRequest();
      nRequest[i].open("GET", URL[i], true);
      nRequest[i].onreadystatechange = function (oEvent) {
         if (nRequest[i].readyState === 4) {
            if (nRequest[i].status === 200) {
              console.log(nRequest[i].responseText);
              alert(nRequest[i].responseText);
            } else {
              console.log("Error", nRequest[i].statusText);
            }
         }
      };
      nRequest[i].send(null);
   })(i);
}

This introduces an immediately invoked function expression for each loop iteration such that the code inside the function has its own i - the magic of JS closures means that when the onreadystatechange function is called it will access the parameter i of the anonymous function (even though that function has completed), not the i of the outer scope, so the right nRequest element will be processed each time.

Also you had a typo on the .open() line where you said wURL[i] but should've had URL[i].

Depending on what you plan to do with the response text I'm not sure that you need an array of requests at all: you could encapsulate the Ajax code into a function that takes a URL and a callback function as parameters, and then call that function in the loop...

making xmlhttprequests, to different servers

You cannot do that. XMLHttpRequest is only allowed to connect to the same domain that the page belongs to. This is called the "same origin policy".

Google "same origin policy" or search for it here on SO to learn more.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!