使用 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 20:31:38  来源:igfitidea点击:

Simple long polling example with JavaScript and jQuery

javascriptjqueryasynchronous

提问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 XMLHttpRequestobject or jQuery's $.ajaxmethod to send a GETor POSTrequest to the server asynchronously requesting some data.

显而易见的开始是使用XMLHttpRequest对象或 jQuery 的$.ajax方法向服务器异步请求一些数据发送GETPOST请求。

However, beyond sending one request at a time using a setIntervalmethod every 30 secondsI 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 setIntervalis 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.ionor WebSocketsbut does usejQueryby taking advantage of its completemethod 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