首页 > 解决方案 > 第二次调用后 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

我哪里做错了? 看看截图

标签: javascripthtmljson

解决方案


您需要重新初始化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()
}

一些不相​​关的建议:

  1. 显式使用true,而不是!0提高可读性。

  2. 你也应该听xhr.onerror。否则,您可能会想知道请求何时失败。


推荐阅读