使用 xampp 在本地主机上运行 index.html 时会出现错误: index.html:17未捕获的InvalidStateError:无法在“XMLHttpRequest”上执行“发送”:对象的状态必须是OPENED.sendAjax @index.html:17onclick @index.html:28
这是index.html 文件:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Show Ajax</title>
<script>
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if(xhr.readyState === 4){
document.getElementById('ajax').innerHTML = xhr.responseText;
}
xhr.open('GET', 'data.html');
};
function sendAjax(){
xhr.send();
document.getElementById('load').style.display = "none";
}
</script>
</head>
<body>
<h1>Bring on ajax</h1>
<button id="load" onClick="sendAjax()">bring it</button>
<div id="ajax">
</div>
</body>
</html>
这是 data.html 文件:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>
</head>
<body>
<p> Hello I'm Ajax, came here on your request</p>
</body>
</html>
最佳答案
您无法在 readyState
处理程序中打开请求,因为该处理程序仅在发出请求时才会触发,打开后,您必须在 之前打开请求ReadyState
处理程序被调用,但在它定义之后,意味着在函数之外,在它之后。
您通常还应该为每次调用 sendAjax
函数创建一个新的请求对象,除非您有充分的理由不这样做
function sendAjax(){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if(xhr.readyState === 4 && xhr.status === 200) {
document.getElementById('ajax').innerHTML = xhr.responseText;
}
};
xhr.open('GET', 'data.html');
xhr.send();
document.getElementById('load').style.display = "none";
}
关于javascript - Ajax错误: index. html :17 Uncaught InvalidStateError: Failed to execute 'send' on 'XMLHttpRequest' : The object's state must be OPENED. sendAjax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39893579/