javascript - 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();
解决方案
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();
推荐阅读
- android - 片段中不可点击的选项菜单项
- vba - 如何通过从类别对话框中选择类别进行搜索?
- pytorch - RuntimeError:给定组 = 1,大小为 [32、3、3、3] 的权重,预期输入 [4、32、6、7] 有 3 个通道,但有 32 个通道
- laravel - 如何更改模块“模块”文件夹名称?
- r - 通过使用 optim() 最小化残差平方和来优化参数,将模型拟合到观测数据
- android - Json$Default 不能转换为 kotlinx.serialization.json.Json
- ios - 如何使用 Swift JSONDecoder 解码可以是数组或单个对象的 JSON 属性?
- mongodb - MongoDB 按年和班级分组然后计数 - 不工作
- vba - 如何检索和存储 JSESSIONID cookie?
- java - 在 ContextInitializer 方法中从 schema.sql 文件执行 sql 语句