gpt4 book ai didi

javascript - XMLHttpRequest.readyState

转载 作者:行者123 更新时间:2023-11-28 02:07:32 30 4
gpt4 key购买 nike

home.html

front page test

测试.php

<SCRIPT language="JavaScript" SRC="ajax.js"></SCRIPT>
<button type="button" onclick="callAJAX('home.html','displaydiv')">Click Me!</button>
<div id="displaydiv"></div>

ajax.js

function callAJAX(url, pageElement, callMessage) {
document.getElementById(pageElement).innerHTML = callMessage;
try {
req = new XMLHttpRequest(); /* e.g. Firefox */
} catch(e) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
/* some versions IE */
} catch (e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
/* some versions IE */
} catch (E) {
req = false;
}
}
}

req.onreadystatechange = function() {responseAJAX(pageElement);};
req.open("GET",url,true);
req.send(null);

}

function responseAJAX(pageElement) {
console.log(req.readyState);
var output = '';
if (req.readyState == 4) {
if (req.status == 200) {
output = req.responseText;
document.getElementById(pageElement).innerHTML = output;
}
}
}

以上代码主要来自here :

问题:

  1. 根据this siteonreadystatechange 存储了一个函数(或函数名称),每次readyState 属性发生变化时都会自动调用,那么readyState 属性什么时候会发生变化呢?在req.send(null);之后?

  2. 对于这一行:console.log(req.readyState);在chrome控制台中,它显示:1 2 3 4,它不输出0 ,是因为0:请求未初始化吗?

最佳答案

readyState 在几个地方发生了变化,查看 Mozilla's documentation了解更多信息。 req.readyState = 0 表示 req.open() 尚未被调用。

另外,取决于what browsers you are trying to support with this code ,您可以考虑使用 XHR2 中的一些功能,包括一个 req.onload() 函数,该函数会将您的代码更改为:

function callAJAX(url, pageElement, callMessage) {
var elem = document.getElementById(pageElement);
elem.innerHTML = callMessage;
var req = new XMLHttpRequest();
req.onload = function() {
elem.innerHTML = req.responseText;
};
req.open("GET",url,true);
req.send(null);
}

关于javascript - XMLHttpRequest.readyState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17561751/

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