javascript - 第二次调用后 Json String 不显示
问题描述
嘿,我是 js 的初学者,我现在面临一个问题,如果可以的话,请帮助我 这是我的 html
<div class="container">
<button id="button1">Get Costumer</button>
<button id="button2">Get Costumers</button>
<br><br>
<h1>Customer</h1>
<div id="Customer"></div>
<h1>Customers</h1>
<div id="Customers"></div>
<div id="output"></div>
</div>
和js
const xhr = new XMLHttpRequest();
console.log(xhr);
xhr.open("GET", "customer.json", !0);
document.getElementById('button1').addEventListener('click', loadCustomer);
console.log(xhr);
function loadCustomer() {
xhr.onload = function() {
console.log(1);
if (this.status === 200) {
const customer = JSON.parse(this.responseText);
console.log(customer)
}
};
xhr.send()
}
当我单击按钮时,它只显示一次并在控制台中引发此错误
app.js:33 未捕获的 DOMException:无法在“XMLHttpRequest”上执行“发送”:对象的状态必须打开。在 HTMLButtonElement.loadCustomer
我哪里做错了? 看看截图
解决方案
您需要重新初始化xhr
内部loadCustomer
方法。只需在该方法中移动初始化代码,它就应该开始工作了。
document.getElementById('button1').addEventListener('click', loadCustomer);
function loadCustomer() {
const xhr = new XMLHttpRequest();
console.log(xhr);
xhr.open("GET", "customer.json", !0);
console.log(xhr);
xhr.onload = function() {
console.log(1);
if (this.status === 200) {
const customer = JSON.parse(this.responseText);
console.log(customer)
}
};
xhr.send()
}
一些不相关的建议:
显式使用
true
,而不是!0
提高可读性。你也应该听
xhr.onerror
。否则,您可能会想知道请求何时失败。
推荐阅读
- bash - Bash date 命令持续更新
- python - 具有不同模式的正则表达式
- python - 使用 pymssql 将文本文件批量插入 SQL Server
- ios - 如何通过点击按钮将焦点设置到视图中的下一个 TextField?
- javascript - Fetch API 获取 php 内容而不是发出请求
- python - 为什么我的函数 gameloop() 无法在 python 中重置我的游戏和 player.rect.x 和 player.rect.y 位置?
- python - 无法卸载“numpy”
- gcc - 将 gcc 添加到系统根映像
- ruby-on-rails - 升级到 Rails 5.2 后出现语法错误
- android - 亚行备份/恢复多用户应用程序?