我有一个显示聊天消息的页面。我需要每隔30秒刷新聊天主体以加载新消息。我已将间隔设置为30秒,该函数正在运行,但它没有发出HTTP请求。这是我的代码
function loadmessages(){
var ids = document.getElementById("pid").value;
var request = new XMLHttpRequest();
request.open("get", '/refresh_message/'+ ids );
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
request.setRequestHeader("X-CSRF-TOKEN", document.querySelector('meta[name="csrf-token"]').content);
request.onload = function(){
if(this.status == 200){
var resp = JSON.parse(this.responseText);
console.log(resp.message);
}
else{
console.log(this.status);
}
request.send(null);
}
}
loadmessages();
setInterval(function(){
loadmessages()
}, 30000);
答案 0 :(得分:2)
一致的缩进很重要。你将request.send(null);
放在request.onload
函数中,所以当然它永远不会被发送到第一位。试着把它放在外面,而不是:
function loadmessages() {
var ids = document.getElementById("pid").value;
var request = new XMLHttpRequest();
request.open("get", '/refresh_message/' + ids);
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
request.setRequestHeader("X-CSRF-TOKEN", document.querySelector('meta[name="csrf-token"]').content);
request.onload = function() {
if (this.status == 200) {
var resp = JSON.parse(this.responseText);
console.log(resp.message);
} else {
console.log(this.status);
}
}
request.send(null);
}