gpt4 book ai didi

javascript - 第一次后再次按ajax按钮会出现奇怪的错误

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

基本上,当我第一次按下按钮时,ajax 加载完美,但是当我再次按下同一个 ajax 按钮时,它会给我这个错误

(index):17 未捕获的 DOMException: 无法对“XMLHttpRequest”执行“发送”:对象的状态必须为 OPENED。 在 sendAJAX ( http://etc.../:17:5 ) 在 HTMLButtonElement.onclick (http://etc.../:29:40)

我找到了有关此问题的文章,但它们令人困惑,以至于我不知道如何将这些解决方案集成到我的脚本中,以使其与我的脚本一起使用,因此我需要一个基于我的确切情况的代码示例解决方案脚本不是基于别人的脚本,所以我可以

根据我的脚本更好地理解这一点。我主要想知道如何才能继续调用相同的 ajax 请求,无论我按下同一个按钮多少次而不会出现错误。

代码示例

index.php

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link href='//fonts.googleapis.com/css?family=Varela+Round' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="css/main.css">
<title>AJAX with JavaScript</title>
<script>
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
document.getElementById('ajax').innerHTML = xhr.responseText;
}
};
xhr.open('GET', 'sidebar.html');
function sendAJAX() {
xhr.send();
}
</script>
</head>
<body>
<div class="grid-container centered">
<div class="grid-100">
<div class="contained">
<div class="grid-100">
<div class="heading">
<h1>Bring on the AJAX</h1>
<button id="load" onclick="sendAJAX()">Bring it!</button>
</div>
<ul id="ajax">

</ul>
</div>
</div>
</div>
</div>
</body>
</html>

sidebar.html

<section>
<h2>Welcome to the wonderful world of AJAX</h2>
<p>This content provided to you dynamically by the XMLHTTP Request Object</p>
</section>

最佳答案

您仅创建一次 xhr 元素,因此如果第二次调用 sendAJAX,则在 上调用 send XMLHttpRequest 已发送。

调用 send 后,xhr 对象的状态不再打开,因此您会收到错误消息。

您可以通过为每个 sendAJAX 调用创建新的 XMLHttpRequest 来解决该问题。

function sendAJAX() {

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
document.getElementById('ajax').innerHTML = xhr.responseText;
}
};
xhr.open('GET', 'sidebar.html');
xhr.send();
}

或者仅将 open 移动到 sendAJAX 中:

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
document.getElementById('ajax').innerHTML = xhr.responseText;
}
};

function sendAJAX() {

xhr.open('GET', 'sidebar.html');
xhr.send();
}

XMLHttpRequest.open()

Note: Calling open for an already active request (one for which open() has already been called) is the equivalent of calling abort().

关于javascript - 第一次后再次按ajax按钮会出现奇怪的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50080408/

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