问题描述
我试图创建一个实时网站分析仪表盘创造一个开放的HTTP连接使用jQuery /异步的JavaScript来更新服务器轮询到数据服务器,当它们发生。
其明显的启动将是使用 XMLHtt prequest
对象或jQuery的 $。阿贾克斯
方法来发送一个 GET
或 POST
请求到服务器异步请求的一些数据。
然而,除了使用的setInterval
方法一次发送一个请求每个我不知道怎么样以向服务器持久的连接。基本上,我只是想发的一个http请求并确保与服务器的连接保持开放投票!
我的例子$ C $与的setInterval
c是如下:
< DIV ID =分析>< / DIV>
<脚本>
VAR分析=的document.getElementById('分析');
的setInterval(函数(){
$阿贾克斯(网址:{url:http://server.com/,成功:功能(数据){
analytics.innerHTML =数据;
},数据类型:JSON});
},30000);
< / SCRIPT>
在线搜索,这是我一直在寻找的答案后为其不使用 sockets.io
也不的WebSockets
,但不使用 的jQuery
通过采取优势其完整
方法来创建一个人工循环:
< DIV ID =分析>< / DIV>
<脚本>
VAR分析=的document.getElementById('分析');
(函数民调(){
$阿贾克斯(网址:{url:服务器,成功:功能(数据){
analytics.innerHTML =数据;
},数据类型:JSON,完整的:民调显示,超时:30000});
})();
< / SCRIPT>
来源为Technoctave田戴维斯:http://techoctave.com/c7/posts/60-simple-long-polling-example-with-javascript-and-jquery
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.
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.
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 request and ensure the connection to the server stays open for polling!
My example code with setInterval
is as follows:
<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>
After searching online, this was the answer I was looking for which doesn't use sockets.io
nor WebSockets
but does use jQuery
by taking advantage of its complete
method to create an artificial loop:
<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
这篇关于使用JavaScript和jQuery简单的长轮询的例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!