简体   繁体   English

使用javascript进行多个HTTP GET请求

[英]making multiple HTTP GET requests with javascript

I am attempting to make multiple http get requests in js. 我试图在js中发出多个http get请求。 but I'm a total noob. 但我完全是菜鸟。 I would not be opposed to jQuery either. 我也不会反对jQuery。 The idea is I make a call to my server so I can populate a js chart. 我的想法是打电话给我的服务器,以便可以填充js图表。

var client;
function handler() { 
    if(client.readyState == 4 && client.status == 200) { 
        // make a chart
    }
} 

window.onload = function() { 
    client = new XMLHttpRequest(); 
    client.onreadystatechanged = handler; 
    client.open("GET", "http://someurl/stuff"); 
    client.send();
}

so the above is the basic idea of a web request. 因此,以上是网络请求的基本概念。 It seems that the handler acts a callback or event. 看来处理程序会执行回调或事件。 this works when creating one get request. 这在创建一个获取请求时起作用。 but if I make two or more, then I get mixed results. 但是如果我获得两个或更多,则结果会好坏参半。 sometimes all requests will work, other times none, or just one. 有时所有请求都可以工作,有时则没有,或者只有一个。 the error that occurs is the connection has not been closed. 发生的错误是尚未关闭连接。

The primary issue with this code is that it uses the same global variables (eg client ) which will just fail for multiple requests as they become clobbered . 这段代码的主要问题是它使用相同的全局变量(例如client ),这些全局变量只会在多个请求变得混乱时失败。

(The issue that the order of the handler invocations is undefined due to the asynchronous nature of the requests is only secondary to the lack of re-entrancy of creating/using the XHR object in the given code - there is no way that the handler is guaranteed the correct XHR object when it access the client variable!) (这个问题的处理程序调用的顺序是不确定的,由于请求的异步性质是仅次于缺乏创建/使用XHR对象在给定的代码的重入的-没有办法,处理程序是当访问client变量时,保证了正确的XHR对象!)

Closures and objects avoid this issue but .. just use jQuery (or whatever library you prefer that provides a nice XHR interface, preferably with Promises). 闭包和对象避免了这个问题,但是..只需使用jQuery(或者您更喜欢提供一个不错的XHR接口的任何库,最好是Promises)。

Since you "would not be opposed to jquery", then use it . 由于您“不会反对jquery”,因此请使用它 Take care to only do work from within the callbacks (or promise handlers) using the returned data they provide - this is because the requests are, well, asynchronous. 注意使用回调函数(或promise处理程序)提供的返回数据在回调(或promise处理程序)中进行工作,这是因为请求是异步的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM