我在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();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句