Javascript XMLHttpRequest不断返回Null
我有一个关于XMLHttpRequest的教程,但是我不知道为什么我的数据返回null。我需要向url发出请求并返回一个随机单词。第一次调用interval时,html将显示加载。。。但每次之后,它都是空白的。谢谢你的帮助 下面是我的HTML的代码片段Javascript XMLHttpRequest不断返回Null,javascript,html,Javascript,Html,我有一个关于XMLHttpRequest的教程,但是我不知道为什么我的数据返回null。我需要向url发出请求并返回一个随机单词。第一次调用interval时,html将显示加载。。。但每次之后,它都是空白的。谢谢你的帮助 下面是我的HTML的代码片段 要添加的数据 下面是我的Javascript代码片段 让obj={ 孤岛加载:false, 加载:函数(){ 如果(此。正在加载){ 返回null; }否则{ this.isLoading=true; } let request=new XM
要添加的数据
下面是我的Javascript代码片段
让obj={
孤岛加载:false,
加载:函数(){
如果(此。正在加载){
返回null;
}否则{
this.isLoading=true;
}
let request=new XMLHttpRequest();
让响应=“加载…”;
请求。addEventListener(“加载”,功能(ev){
响应=ev.target.response;
this.isLoading=false;
console.log('event log',response)//按预期记录“Random Words API”
});
请求。打开(“获取”https://random-words-api.vercel.app/");
request.send();
返回响应
}
};
setInterval(函数(){
let response=obj.load();
console.log('line 25',response)//日志加载…然后在第一次加载之后每次都为null
document.getElementById(“添加文本”).innerText=响应;
}, 4000);
这是我这边的
} else {
this.isLoading = true;
}
并更新这部分代码以显示响应数据
request.addEventListener("load", function (ev) {
response = ev.target.response;
this.isLoading = false;
console.log('event log', response); //logs "Random Words API" as expected
document.getElementById("content").append(response);
// or you can keep add-text id document.getElementById("add-text").append(response);
});
我刚刚删除了else block语句,当您在函数中使用
return
停止执行return
后,请尝试删除此块。因此load()每次都在return null
行停止,因为this.isload
已设置为true
。您的目标是什么?您的else
块将isLoding设置为true
,因此之后它将在if
语句中返回null
。重新格式化您的if-else
块以符合您的要求。我想显示加载。。。直到有东西从GET返回。然后我想显示这个响应@fortune加载事件侦听器中的此
引用的是XMLHttpRequest
实例,而不是您的obj
对象。另外,您的代码是异步的,因此返回响应将无法正常工作。如果我这样做,它将显示正在加载。。。永远不变,但它正在打印控制台json响应t,加载后追加响应…更新这部分代码请求。addEventListener(“加载”,函数(ev){response=ev.target.response;this.isLoading=false;console.log('event log',response);//logs“Random Words API”如预期的document.getElementById(“内容”).append(响应);//或者您可以保留add text id document.getElementById(“add text”).append(响应);});