Ajax错误:index.html:17 Uncaught InvalidStateError:无法在'XMLHttpRequest'上执行'send':对象的状态必须是OPENED.sendAjax

时间:2016-10-06 10:27:12

标签: javascript html ajax

使用xampp在本地主机上运行index.html时会出错: index.html:17 Uncaught InvalidStateError:无法在'XMLHttpRequest'上执行'send':对象的状态必须是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>

1 个答案:

答案 0 :(得分:0)

您无法在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";
}