作者:宝宝田小丫 | 来源:互联网 | 2023-05-18 02:35
我正在开发一个项目,我有两个XMLHttpRequest()对象,比如A和B.
我想要完成的是当A完成获取数据项列表时,将触发B以根据以前获取的先前数据项获取更多项.
目前我的问题是两个对象彼此独立工作.
我的代码如下:
var A = new XMLHttpRequest();
var B = new XMLHttpRequest();
A.open("GET", directory, true);
A.Onreadystatechange= function () {
if (A.readyState === 4) {
if (A.status === 200 || A.status == 0) {
//does... something
}
}
}
A.send(null);
while(true){
B.open("GET", another_directory, false);
B.overrideMimeType("application/document");
B.send(null);
if (B.status == "404")
continue;
//does... something else
}
此代码无法正常工作,因为我发现在A完成之前,evertime B会继续进行.我基本上不知道要使用哪个事件.
我怎样才能实现目标?我可以使用哪些事件以便在完成A后立即同步处理B.
1> 小智..:
好的,让我们从你的代码开始吧.我已经添加了一些评论,所以现在您可以了解问题的根源:
var A = new XMLHttpRequest(); //You create an XMLHttpRequest object
var B = new XMLHttpRequest(); //And an another
A.open("GET", directory, true);
/* Now you open a GET request to DIRECTORY, with async TRUE. The third parameter can
make a request sync or async, but sync is not recommended as described below. */
A.Onreadystatechange= function () {
if (A.readyState === 4) {
if (A.status === 200 || A.status == 0) {
/* So you registered an event listener. It runs when the readyState changes.
You can use it to detect if the request is finished or not. If the readyState is
4, then the request is finished, if the status code is 200, then the response is
OK. Here you can do everythin you want after the request. */
}
}
}
A.send(null); //Now you send the request. When it finishes, the event handler will
// do the processing, but the execution won't stop here, it immediately goes to the
// next function
while(true){ // Infinite loop
B.open("GET", another_directory, false); //Open request B to ANOTHER_DIRECTORY,
// but now, request B will be synchronous
B.overrideMimeType("application/document"); // Configure mime type
B.send(null); // Send the request
if (B.status == "404")
continue;
// If it's not found, then go to the next iteration
// and do something else
}
我希望现在你可以看到问题的根源.当您运行此脚本时,您启动异步请求,然后立即启动下一个.现在您可以选择2种方式.
从回调运行下一个请求(推荐)
这是更好的方式.因此,启动您的第一个(异步)请求,并在事件监听器(您进行处理)中,您可以启动下一个请求.我在这里做了一个评论的例子:http://jsfiddle.net/5pt6j1mo/1/
(你可以在没有数组的情况下做到 - 这只是一个例子)
如果使用这种方式,那么在等待响应之前,GUI不会冻结.一切都将负责,以便您可以与页面进行交互,您可以创建取消按钮等.
同步AJAX(不推荐)
我不推荐它,因为Chrome中的"主线程上的同步XMLHttpRequest已被弃用",但如果您真的想要,那么您可以尝试使用此解决方案.所以XMLHttpRequest的open函数有3个参数:
方法:使用哪种HTTP methid
URL:要请求的URL
ASYNC:异步请求?如果为false,则它将是同步的,这意味着在您调用.send()之后,它将暂停执行,直到响应返回.
因此,如果您将第三个参数设置为FALSE,那么您可以轻松地执行此操作......但您不应该这样做!
2> Benjamin Gru..:
这是一个替代解决方案,使用fetch API或promisify native XHR,这个问题变得更加简单:
fetch(directory).then(function(response){
// some processing
return fetch(another_directory); // can change content type too, see the mdn docs
}).then(function(responseTwo){
// all processing is done
}).catch(function(err){
// handle errors from all the steps above at once
});
这与XHR一样原生,并且使用promises管理要简单得多.