[英]From polling to long polling
所以我有一个脚本,它使用基本轮询来实时显示数据库中的记录总数
所以没有什么复杂的,所以任何人都可以给我一个长轮询结构的代码示例。 我之所以问这个问题是因为谷歌上的所有文章
搜索为我提供了 jQuery 示例我似乎无法找到一个在我的情况下有意义的普通 JavaScript 示例。 这是我正在运行的代码的 .gif 屏幕截图,因此你们知道我的详细意思。
这是我需要转换或更改为长轮询的基本轮询示例代码。
索引.php
<style>
#label{
margin: 0;
color: red;
font-weight: bold;
}
</style>
<script>
document.addEventListener('DOMContentLoaded',function(){
/**********************************************************************
Check for a new record amount in the data base
**********************************************************************/
function checkForNewRecords(){
var xhr= new XMLHttpRequest();
xhr.onreadystatechange= function(){
if(xhr.readyState == 4){
document.querySelector('#output').innerHTML= xhr.responseText;
}
}
xhr.open('POST','check-for-new-records.php');
xhr.send();
}
setInterval(function(){checkForNewRecords()},1000);
});
</script>
<p id='label'>Total records in the database in real time in basic polling</p>
<div id='output'></div>
检查新记录.php
<?php
$db_servername= 'localhost';
$db_username='jd';
$db_password= '1234';
$db_name= 'test';
$db_connect= new mysqli($db_servername,$db_username,$db_password,$db_name);
$db_query= "SELECT COUNT(id) AS id FROM example";
$db_result= $db_connect->query($db_query);
$db_row= $db_result->fetch_object();
$total_records= $db_row->id;
?>
<style>
#total-records{
margin-top: 0;
}
</style>
<p id='total-records'><?php echo $total_records; ?></p>
那么你们如何将其转换为长轮询,请不要建议其他方法或不要提供没有帮助的答案我只对我要求的内容感兴趣,我很确定其他人也是也对纯 JavaScript 版本感兴趣,我之所以这么说是因为我
在网上询问这个话题很长时间了,似乎没有人有兴趣回答这个问题,或者他们认为回答这个问题太难了,如果是这样,为什么有这么多关于这个话题的 jQuery 示例而不是基于纯 JavaScript 并且不是每个人都喜欢使用库。 我只是说我对我从这个基于纯 JavaScript 的主题中得到的无用答案感到不满意,请注意。
你不应该使用setInterval
而是使用setTimeout
。
如果您使用setTimeout
那么轮询和长轮询的基本区别仅在于延迟发生的地方。 对于轮询,服务器将立即响应(即使没有发生任何更改),客户端将等待 n 秒以发送下一个请求。 对于长轮询,服务器将等待响应,直到新数据可用(或发生超时),客户端将在收到响应时立即发送新请求。
使用XMLHttpRequest
、 fetch
或jQuery
实现它绝对没有什么不同,客户端唯一的区别是下一个请求的延迟。
轮询:
function checkForNewRecords() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
document.querySelector('#output').innerHTML = xhr.responseText;
setTimeout(checkForNewRecords, 1000); // polling has the delay on the client
}
}
xhr.open('POST', 'check-for-new-records.php');
xhr.send();
}
checkForNewRecords()
长轮询:
function checkForNewRecords() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
document.querySelector('#output').innerHTML = xhr.responseText;
setTimeout(checkForNewRecords, 0);
// long-polling has the delay on the server
// the client initiates a new request immediatly after receiving the response.
}
}
xhr.open('POST', 'check-for-new-records.php');
xhr.send();
}
checkForNewRecords()
另一方面,在服务器端,您通常必须更改一些内容才能使长轮询有效地工作。
轮询和长轮询针对优化的重要区别在于如何告诉服务器何时发送更新信息,但这完全独立于您用于请求数据的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.