首页 > 解决方案 > XHR 内更新的文档元素为空

问题描述

我在 p5.js 绘制函数中有这段代码(我放了 noLoop,所以我不会被错误溢出),当我运行它时,在它从 DOM 元素读取的部分,我得到一个 JSON 错误。当我打印出来时,我得到一个空字符串。但是当我检查元素时,元素中有文本。我该如何解决?代码如下。注意:由于一个错误,我不得不做这种非常笨拙的做事方式。

var xhr = new XMLHttpRequest();
xhr.onreadystatechange=function(){
    document.getElementById("players").innerHTML = xhr.responseText;
}
xhr.open("GET","/rusers", true);
xhr.send();
...
fill(0,0,255);
dataj = JSON.parse(document.getElementById("players").innerHTML);
for (let d of dataj){
    circle(d.x,d.y);
}
noLoop();

标签: javascriptdomxmlhttprequestp5.js

解决方案


You do not wait for the Ajax call to complete, you just assume that it is there when the next part of the code runs. You also do not check to make sure the XMLHttpRequest is done loading.

Basic idea:

const xhr = new XMLHttpRequest();

xhr.open("GET", "/rusers", true);
xhr.onreadystatechange = function () {
  if(xhr.readyState === XMLHttpRequest.DONE) {
    var status = xhr.status;
    if (status >= 200 && status < 400) {
      // The request has been completed successfully
      document.getElementById("players").innerHTML = xhr.responseText;
      // Your logic here
      fill(0,0,255);
      const dataj = JSON.parse(document.getElementById("players").innerHTML);
      for (let d of dataj){
        circle(d.x,d.y);
      }
      noLoop();
    } else {
      alert('error');
    }
  }
};
xhr.send();

推荐阅读