我正在处理我的第一个 AJAX 项目,我已经开始设置以下功能:
function sendHTTPRequest(callback,filename,data) {
if (window.XMLHttpRequest) {
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
httpRequest.onreadystatechange = callback;
httpRequest.open('POST',rootAddress+filename, true);
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
httpRequest.send(data);
}
function exampleCallback() {
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
// successful, parse the XML data
} else {
// error
}
} else {
// not ready
}
}
这很有效,但我现在已经到了这样的地步:我有多个并发 HTTP 请求,而我的单个全局 httpRequest
变量并没有削减它。在我看来,每次调用 sendHTTPRequest()
时,我都可以使用一个数组,并 .push
将一个新的 XMLHttpRequest 放到堆栈上,但是我该如何告诉我的各种回调函数要解析堆栈中的哪个项目?或者是处理此过程的更好方法? (我使用它们来处理对不同页面的请求,结果需要以不同方式解析。)
谢谢!
最佳答案
使用局部变量和每个请求的回调,后者又会调用给定的回调。所需的更改非常小;参见 **
行:
function sendHTTPRequest(callback,filename,data) {
var httpRequest; // ** Local variable
if (window.XMLHttpRequest) {
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
// ** Callback specific to *this* request
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
// successful, call the callback
callback(httpRequest);
} else {
// error, call the callback -- here we use null to indicate the error
callback(null);
}
} else {
// not ready
}
};
httpRequest.open('POST',rootAddress+filename, true);
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
httpRequest.send(data);
}
function exampleCallback(xhr) {
if (xhr) {
// successful, parse the XML data, for instance
var x = xhr.responseXML;
} else {
// not ready
}
}
您可以让它为回调提供更多信息(例如,filename
和 data
参数)。
如果您使用 promises,您可以让 sendHTTPRequest
返回一个 promise 而不是接受直接回调。
关于javascript - 如何管理多个重叠的 XMLHttpRequests?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38618031/