gpt4 book ai didi

javascript - xmlHttpRequest .open() 方法中的参数 "true"

转载 作者:行者123 更新时间:2023-12-03 00:58:44 25 4
gpt4 key购买 nike

从我在 MDN 中读到的引用资料来看,它说

If TRUE (the default), the execution of the JavaScript function will continue while the response of the server has not yet arrived.

This is the A in AJAX.

我一直在使用 AJAX,但是当我读到它时我有点困惑。我认为问题可能是我没有清楚地理解AJAX概念。我当然知道 AJAX 不会刷新页面,这意味着与服务器的连接和响应完全在后台完成。

但是根据该引用资料,我可以想象如果我的 JavaScript 中有这样的代码:

//true, therefore process the function while server retrieves url
var xmlResponse;
var url = "http://example.com/file.xml";
xml_req.open("GET", url, true);

xml_req.onreadystatechange = function() {
if(xml_req.readyState == 4 && xml_req.status == 200) {
if(xml_req.responseText != null)
xmlResponse = xml_req.responseXML; //server response may not yet arrive
else {
alert("failed");
return false;
}
};
xml_req.send(null);

这是否意味着 xmlResponse 可能未定义,因为服务器仍在检索数据?有人能解释一下 AJAX 技术的执行流程到底是什么吗?提前致谢。

最佳答案

我写了一篇更详细的文章here ,但这是基本思想。

将其设置为 true 意味着您正在发出异步请求。这意味着在 http 请求完成之前代码不会暂停。同步调用会锁定浏览器,因此其他任何操作都不会运行。这可能会导致问题,因此人们更喜欢异步。

XHR 对象向我们通报它正在做什么。它为我们提供了 onreadystatechange 事件的更新。我们向它注册一个函数,以便我们可以跟踪它的状态。 onreadystatechange 被调用 4 次。每个都有不同的状态

0 = uninitialized
1 = loading
2 = loaded
3 = interactive
4 = complete

当readystate为4时,数据可供我们使用。

现在在您发布的代码中,它正在检查完整状态并确保状态为 200 [ok]

if(xml_req.readyState == 4 && xml_req.status == 200){

如果您在返回之前尝试在代码中的其他位置使用 xmlResponse 的值,则该值将是未定义的。一个例子

ml_req.send(null);
alert(xmlResponse );

关于 XMLHttpRequest 的第一篇文章可能适合您阅读。 Apple Article on xmlhttpreq

关于javascript - xmlHttpRequest .open() 方法中的参数 "true",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6461958/

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