使用 JavaScript 和 jQuery 的简单长轮询示例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14027005/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Simple long polling example with JavaScript and jQuery
提问by technojas
I'm trying to create a real-time website analytics dashboard which creates an open HTTP connection to the server using jQuery/JavaScript asynchronously to poll the server for updates to the data as and when they occur.
我正在尝试创建一个实时网站分析仪表板,该仪表板使用 jQuery/JavaScript 异步创建到服务器的开放 HTTP 连接,以在数据更新发生时轮询服务器以获取数据更新。
The obvious start for this would be to use an XMLHttpRequest
object or jQuery's $.ajax
method to send a GET
or POST
request to the server asynchronously requesting some data.
显而易见的开始是使用XMLHttpRequest
对象或 jQuery 的$.ajax
方法向服务器异步请求一些数据发送GET
或POST
请求。
However, beyond sending one request at a time using a setInterval
method every 30 seconds
I am not sure how to make the connection to the server persistent. Basically, I only want to send one http requestand ensure the connection to the server stays open for polling!
但是,除了使用一种setInterval
方法一次发送一个请求之外,30 seconds
我不确定如何使与服务器的连接持久。基本上,我只想发送一个 http 请求并确保与服务器的连接保持打开以进行轮询!
My example code with setInterval
is as follows:
我的示例代码setInterval
如下:
<div id="analytics"></div>
<script>
var analytics = document.getElementById('analytics');
setInterval(function(){
$.ajax({ url: "http://server.com/", success: function(data){
analytics.innerHTML = data;
}, dataType: "json"});
}, 30000);
</script>
回答by technojas
After searching online, this was the answer I was looking for which doesn't usesockets.io
nor WebSockets
but does usejQuery
by taking advantage of its complete
method to create an artificial loop:
在网上搜索后,这是我一直在寻找这个问题的答案不使用sockets.io
,也不WebSockets
但不会使用jQuery
利用其优势complete
的方法来创建一个人工循环:
<div id="analytics"></div>
<script>
var analytics = document.getElementById('analytics');
(function poll(){
$.ajax({ url: "server", success: function(data){
analytics.innerHTML = data;
}, dataType: "json", complete: poll, timeout: 30000 });
})();
</script>
Source is Tian Davis from Technoctave: http://techoctave.com/c7/posts/60-simple-long-polling-example-with-javascript-and-jquery
来源是来自 Technoctave 的 Tian Davis:http://techoctave.com/c7/posts/60-simple-long-polling-example-with-javascript-and-jquery