如何处理同时的javascript xmlhttprequests? [英] How to handle Simultaneous javascript xmlhttprequests?

查看:139
本文介绍了如何处理同时的javascript xmlhttprequests?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

将索引从for循环传递给ajax回调函数(javascript)

为了获取一些内容,我对将xmlhttprequests制作到不同的服务器感到有些困惑..
这是我写的,但似乎我在某些时候错了..

I've been a little confused with making xmlhttprequests, to different servers, in order to fetch some content.. Here is what I've written, but it seems that I'm mistaken at some point..

var URL = new Array();
URL[0] = "http://www.example1.com";
URL[1] = "http://www.example2.com";
URL[2] = "http://www.example3.com";
var nRequest = new Array();
for (var i=0; i<3; 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);
}

在IE10上使用此代码我在控制台上被拒绝访问..

with this code on I.E.10 I get access denied on console..

如果我删除数组并使用简单请求,它会按预期运行..

If I remove array and use simple request, it operates as expected..

wRequest = new XMLHttpRequest();
wRequest.open("GET", "http://www.example1.com", true);
wRequest.onreadystatechange = function (oEvent) {
    if (wRequest.readyState === 4) {
        if (wRequest.status === 200) {
            console.log(wRequest.responseText);
            alert(wRequest.responseText);
        } else {
            console.log("Error", wRequest.statusText);
        }
    }
};
wRequest.send(null);

但我怎么能触发多个2-3个请求,但仍然没有数据处理问题??

But how am I supposed to trigger multiple 2-3 requests, and still not have problem with data handling..??

推荐答案

问题(忽略了slebetman所涵盖的跨域问题)是当你的就绪状态改变回调被触发时它是在循环完成后使用来自包含范围的 i 变量,该变量将是 3 。解决这个问题的一种方法如下:

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);
}

这为每个循环迭代引入了一个立即调用的函数表达式,使得里面的代码该函数有自己的 i - JS闭包的神奇之处在于,当调用 onreadystatechange 函数时,它将访问参数 i 的匿名函数(即使该函数已经完成),而不是外部作用域的 i ,所以每次都会处理正确的 nRequest 元素。

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.

此外,你在 .open()你说 wURL [i] 的行,但是应该有 URL [i]

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

根据您计划对响应文本执行的操作,我不确定您是否需要一系列请求:您可以封装将Ajax代码转换为一个函数,该函数将URL和回调函数作为参数,然后在循环中调用该函数...

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...

这篇关于如何处理同时的javascript xmlhttprequests?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆