gpt4 book ai didi

javascript - 如何使用一个依赖于另一个的 2 个 XMLHttpRequest?

转载 作者:可可西里 更新时间:2023-11-01 02:30:08 26 4
gpt4 key购买 nike

我正在做一个项目,我有 2 个 XMLHttpRequest() 对象,比如 A 和 B。

我想要完成的是当A完成获取数据项列表时,将触发B根据A之前获取的数据项获取更多项。

目前我的问题是这两个对象彼此独立工作。

我的代码如下:

            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
}

此代码无效,因为我发现 B 总是在 A 完成之前进行。我基本上不知道使用哪个事件。

我怎样才能实现我的目标?我可以使用哪些事件以便在处理 A 后立即同步处理 B?

最佳答案

好的,让我们从您的代码开始吧。我已经向它添加了一些评论,所以现在您可以了解问题的根源了:

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 个参数:

  • METHOD:要使用的 HTTP 方法
  • URL:请求哪个URL
  • ASYNC:异步请求?如果为 false,那么它将是同步的,这意味着在您调用 .send() 之后,它将暂停执行直到响应返回。

因此,如果您将第三个参数设置为 FALSE,那么您可以轻松地做到这一点……但您不应该这么做!

关于javascript - 如何使用一个依赖于另一个的 2 个 XMLHttpRequest?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29051807/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com