javascript - Ajax错误: index. html :17 Uncaught InvalidStateError: Failed to execute 'send' on 'XMLHttpRequest' : The object's state must be OPENED. sendAjax

标签 javascript html ajax

使用 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/

相关文章:

javascript - 比较 JS 中 2 个对象的属性集以找出哪些属性发生了变化以及发生了什么变化?

javascript - 如何给网页添加背景音乐?

javascript - 使用 jQuery 从原始 css 文件中获取值

javascript - 模拟测试 http - angular2

javascript - 在不使用 eval 的情况下通过字符串名称访问命名空间的 javascript 对象

javascript - 单击时更改 javascript 中的类

javascript - 在 MaterializeCss Toast 中添加 Material 图标?

javascript - jquery $.ajax get 将通过 http 获取文件,但在直接与服务器对话时失败,X-Requested-With 设置不正确?

php - 从 postgres 获取数据到 php 再到 html(使用 ajax)

AJAX Post 到 Controller 操作 MVC.NET 后,jQuery UI Draggable 和 Droppable 中断