javascript - PHP - 长轮询,页面不断加载
问题描述
我不明白为什么,但是我的 ajax 代码请求的 PHP 文件中的循环使我的浏览器在加载页面时冻结
PHP代码:
ini_set('max_execution_time', 0);
ignore_user_abort(false);
$isUptodate = (bool) file_get_contents($this->uptodateFile);
while ($isUptodate === true)
{
sleep(1);
$isUptodate = (bool) file_get_contents($this->uptodateFile);
}
$updateUptodateFile = fopen($this->uptodateFile, 'w');
fwrite($updateUptodateFile, 'true'); // when something is inserted into my db, the file contains a false value
$jsonData = json_decode(file_get_contents($this->updateFile), true);
echo json_encode(['updates' => count($jsonData)]);
JS代码:
checkForUpdates: function ()
{
var that = this;
$.ajax({
url: 'updates.php',
type: 'GET',
dataType: 'json',
timeout: 10000,
}).done(function (data)
{
console.log('Went OK');
if (data.updates)
{
alert('there is new!');
setTimeout(function () { that.checkForUpdates() }, 5000);
}
}).fail(function (data)
{
console.log(data);
setTimeout(function () { that.checkForUpdates() }, 10000);
});
}
你知道哪里出错了吗?这很奇怪,因为默认的 ajax 异步参数是 true,所以它不应该冻结我的浏览器......
解决方案
推荐阅读
- c# - 如何在查询中获得多个结果?
- sql - 如何使用 Bigquery 通过前缀选择结构中的字段列表
- java - 用新数据刷新anychart饼图
- python - 如何通过每个项目的多个条目对df进行分组,添加列
- firebase - 客户端离线,获取文档失败
- c - 如何使用 .txt 文件作为命令行输入,使其内容被读取为 C 中的命令行输入?
- javascript - 在 React Multi Form 上提交后清除输入
- asp.net-mvc - 实体框架中的三表模型中的 NullReferenceException
- velo - 如何计算 Wix 数据库中的元素数量?
- python - StanfordCoreNLP 服务器使用 Stanza 无限期监听