Javascript使定期间隔的HTTP请求无法正常工作

时间:2018-03-29 21:08:21

标签: javascript

我有一个显示聊天消息的页面。我需要每隔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);

1 个答案:

答案 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);
}