Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/386.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 第二次调用后,Json字符串不显示_Javascript_Html_Json - Fatal编程技术网

Javascript 第二次调用后,Json字符串不显示

Javascript 第二次调用后,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>

嘿,我是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>
当我点击按钮时,它只显示一次,并在控制台中抛出这个错误

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()
    }