【发布时间】:2017-12-08 20:04:32
【问题描述】:
我正在玩 AJAX 长轮询,并尝试通过单击按钮来读取/更新 MySQL 单元格中的简单计数器(数字)值。
PHP 创建一个无限的while 循环,并检查相应单元格中的值是否已被修改(MySQL “current_timestamp”,UNIX)。如果它具有并且 current_timestamp 值大于进行 AJAX 调用的时间戳,它将打破循环并将更新的值和更新的 current_timestamp 发送到客户端。 AJAX 处理数据。
问题:它可以工作,但过了一会儿我得到一个 503 错误。我猜这显然是 while 循环或通过其他浏览器中的多个窗口打开的其他连接(用于测试)。
PHP-文件 text.php:
// Connect to database
$con = mysql_connect('XX', 'XX', 'XX');
if (!$con)
{
die('Error' . mysql_error());
}
mysql_select_db('X', $con);
// Get data
$query = mysqli_query("SELECT counter_value, last_modified FROM content WHERE X = 'X' ORDER BY X DESC");
// Start infinite loop
set_time_limit(0);
while (true)
{
// The timestamp of the last ajax call = the last modified timestamp
$last_ajax_call = $_GET['timestamp'];
clearstatcache();
// Get the value of the counter and the last modified timestamp
while($row = mysql_fetch_array($query))
{
$counter_value = $row['counter_value'];
$last_modified= strtotime($row['last_modified']);
}
// If the time of the last modified timestamp is bigger/later than the last ajax call
if ($last_modified > $last_ajax_call)
{
$result = array(
'counter_value' => $counter_value,
'timestamp' => $last_modified
);
$json = json_encode($result);
echo $json;
break;
// If not, try again in 3 seconds
} else
{
sleep(3);
continue;
}
}
// Close database
mysql_close($con);
js-File中的AJAX部分:
function getContent()
{
// get timestamp of last modified stored in attribute. The initial/first timestamp attribute is set beforehand.
var timestamp = $('#timestamp').attr('data-timestamp');
$.ajax(
{
type: 'GET',
url: 'test.php',
async: true,
cache: false,
data: {timestamp:timestamp},
success: function(data){
var obj = jQuery.parseJSON(data);
$("#counter").text(obj.counter_value);
$("#timestamp").attr("data-timestamp", obj.timestamp);
getContent();
}
}
);
}
getContent();
所以结果是一个 503 错误,该错误在 ca 之后消失。 10 分钟,它又开始工作了。
(任何拼写错误/格式可能是清理代码的结果。) 我刚开始学习PHP和JS,所以可能会有一些新手错误或奇怪的行,请多多关照。非常感谢任何有关优化代码的建议!
【问题讨论】:
-
由于 ajax 是异步的,因此您的 getContent 函数正在调用自身并进入无限死循环。仅供参考:有一个名为 getJSON 的 jQuery 方法,它更易于用于您实际执行的操作。如我所见,您正在尝试模拟实时 TCP 套接字。你看过使用 WebSocket 协议的 Node.js 和 socket.io 吗?
标签: php jquery ajax database long-polling