Comet - показывает ошибку PHP

Я новичок в комете и делаю простое приложение. Мой HTML-файл выглядит так

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>testing comet</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script type="text/javascript" src="jquery-1.9.0.js"></script>
  </head>
  <body>

<div id="content">
</div>

<p>
  <form action="" method="get" onsubmit="comet.doRequest($('#word').val());$('#word').val('');return false;">
    <input type="text" name="word" id="word" value="" />
    <input type="submit" name="submit" value="Send" />
  </form>
</p>

<script type="text/javascript">
// comet implementation
var Comet = function (data_url) {
  this.timestamp = 0;
  this.url = data_url;  
  this.noerror = true;
//alert(data_url);
  this.connect = function() {
    var self = this;

    $.ajax({
      type : 'get',
      url : this.url,
      dataType : 'json', 
      data : {'timestamp' : self.timestamp},
      success : function(response) {
        self.timestamp = response.timestamp;
        self.handleResponse(response);
        self.noerror = true;          
      },
      complete : function(response) {
        // send a new ajax request when this request is finished
        if (!self.noerror) {
            alert("error");
          // if a connection problem occurs, try to reconnect each 5 seconds
          setTimeout(function(){ comet.connect(); }, 5000);           
        }else {
          // persistent connection
          self.connect(); 
        }

        self.noerror = false; 
      }
    });
  }

  this.disconnect = function() {}

  this.handleResponse = function(response) {
    $('#content').append('<div>' + response.msg + '</div>');
  }

  this.doRequest = function(request) {
      $.ajax({
        type : 'get',
        url : this.url,
        data : {'msg' : request}
      });
  }

}

var comet = new Comet('./backend.php');
comet.connect();
</script>

</body>
</html>

backend.php выглядит так

<?php
$dr=DIRECTORY_SEPARATOR;
$filename  = dirname(__FILE__).$dr.'data.txt';

// store new message in the file
$msg = isset($_GET['msg']) ? $_GET['msg'] : '';
if ($msg != '')
{
  file_put_contents($filename,$msg);
  die();
}

// infinite loop until the data file is not modified
$lastmodif    = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;
$currentmodif = filemtime($filename);
while ($currentmodif <= $lastmodif) // check if the data file has been modified
{
  usleep(10000); // sleep 10ms to unload the CPU
  clearstatcache();
  $currentmodif = filemtime($filename);
}

// return a json array
$response = array();
$response['msg']       = file_get_contents($filename);
$response['timestamp'] = $currentmodif;
echo json_encode($response);
flush();

data.txt содержит пустой файл.

Теперь мой вопрос

if (!self.noerror) {
      alert("error");

Это выполнит и покажет предупреждение "ошибка" всегда. Но это работает отлично, если я прокомментирую эту тревожную часть. Что-то не так?

Когда я отслеживаю процесс с помощью firebug, на этих запросах появляется фатальная ошибка, подобная этой.

Любой, пожалуйста, помогите мне Спасибо заранее

2 ответа

Решение

Время ожидания будет вызвано тем, что ваш цикл while не может завершиться до выхода из PHP, поскольку значение параметра max_execution_time Директива была достигнута. Вы могли бы расширить это, но действительно ли вы хотите, чтобы скрипты работали так долго? Я был бы более склонен выполнять больше работы с JavaScript - заставлять его запрашивать обновление каждую секунду или около того (10 мс - это слишком, слишком часто).

Учитывая alert("error")Будьте осторожны, когда вы устанавливаете значение noerror - Вы действительно хотите установить его в false в конце complete() функционировать? Я думаю, что вы хотите изменить свой звонок на $.ajax() к чему-то более похожему (сокращенно):

$.ajax({
    error : function() {
        // the request failed
        setTimeout(function() { comet.connect(); }, 5000);
    },
    success : function(response) {
        // the request succeeded
        self.connect();
    }
});

Если можете, удалите noerror переменная целиком и использовать error() а также success() обратные вызовы для размещения вашей логики для каждого сценария, как описано выше.

Вы должны отредактировать строки backend.php;

<?php
   $dr=DIRECTORY_SEPARATOR;
   ini_set('max_execution_time', 300);
   $filename  = dirname(__FILE__).$dr.'data.txt';
Другие вопросы по тегам