XHR 中更新的文档元素为空

Document element updated inside XHR is null

我在 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();

您无需等待 Ajax 调用完成,您只需假设它在下一部分代码运行时就已存在。您也不检查以确保 XMLHttpRequest 已完成加载。

基本思路:

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