首页 > 解决方案 > 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,所以它不应该冻结我的浏览器......

标签: javascriptphplong-polling

解决方案


推荐阅读