Javascript 第二次调用后,Json字符串不显示
嘿,我是js的初学者,我现在面临一个问题,如果你能帮助我 这是我的htmlJavascript 第二次调用后,Json字符串不显示,javascript,html,json,Javascript,Html,Json,嘿,我是js的初学者,我现在面临一个问题,如果你能帮助我 这是我的html <div class="container"> <button id="button1">Get Costumer</button> <button id="button2">Get Costumers</button> <br><br> <h1>Customer</h1>
<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>
当我点击按钮时,它只显示一次,并在控制台中抛出这个错误
app.js:33未捕获的DomeException:未能对“XMLHttpRequest”执行“发送”:必须打开对象的状态。
在HTMLButtonElement.loadCustomer
我哪里出错了?
您需要在
loadCustomer
方法中重新初始化xhr
。只要将初始化代码移到该方法中,它就会开始工作
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
。否则,您可能会想知道请求何时失败移动xhr.open(“GET”、“customer.json”、!0);在你的loadCustomer()中,它起了作用,非常感谢兄弟@ManojYadavthat
!完成0
是因为将我的代码粘贴到某个在线迷你程序中,先生,感谢您宝贵的时间和对我的指导。
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()
}