没有jQuery的简单XHR长轮询

时间:2014-02-14 21:00:25

标签: javascript node.js http long-polling

我想尝试一个简单的长轮询系统(是的,我想要使用任何现成的scipt,因为我想从中学习)。我正在使用节点服务器,我可以轻松地将我的数据管道/写入客户端,而无需调用result.end();。我应该怎么做这个客户端?我只是希望这对于使用ie< = 9的用户来说是一个简单且不太好的后备,因为更好的浏览器可以获得快速且易于使用的websocket。

长问题简:如何在没有jQuery或其他框架的普通JS中进行长轮询? (或者有一种比长轮询更好的方法)。

1 个答案:

答案 0 :(得分:1)

以下是您要找的内容吗?

  var xhr = new XMLHttpRequest();
  xhr.responseType = 'blob';//or 'text', 'json', ect. there are other types. 
  xhr.timeout = 60000;//milliseconds until timeout fires. (1 minute)
  xhr.onload = function(e2){
    var blob = xhr.response;
    //handle response data
  }
  xhr.ontimeout = function(){
    //if you get this you probably should try to make the connection again.
    //the browser should've killed the connection. 
  }
  xhr.open('GET', "/path/to/URL.cmd?param1=val1&param2=val2", true);
  xhr.send();

我认为timeout属性是使长轮询工作的关键,更多信息请参见spec,在同一文档中有更多关于responseType的信息。如果未指定超时,则默认值为零。

相关问题