已经提到过两次了,但我还是想强调一下。您永远不会希望客户端能够直接访问数据库。这是一个严重的安全风险。
现在来解决问题。首先,您需要设置一个可以使用 ajax 请求的 PHP 文件。我们称之为check.php,它看起来像这样:
<?php
// include necessary files to enable connection to the database
$query = "SELECT number, name FROM members WHERE id=1";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$number = $row['number'];
// send correct content type header of json
header("Content-Type", "application/json");
// we create an array, and encode it to json
// then echo it out while killing the script
die(json_encode(array('numbers'=>$number)));
现在到 JavaScript。该解决方案类似于 Kyle Humfeld 的解决方案,但不会使用 setInterval,因为这是一个非常糟糕的做法。这背后的原因是setInterval 不会关心您的 ajax 调用的状态,无论它是否已完成。因此,如果服务器出现问题,您最终可能会收到堆叠请求,这并不好。
因此,为了防止这种情况,我们改为使用 ajax 方法的 success-callback(.getJSON 本质上是 .ajax 的简写)和 setTimeout 的组合来创建称为 polling 的东西:
$(function(){
// placeholder for request
var request = null;
// request function
var check = function() {
request = $.getJSON('check.php', function(data){
// this will log the numbers variable to the dev console
console.log(data.numbers);
// initiate a timeout so the same request is done again in 5 seconds
setTimeout(check, 5000);
});
});
// initiate the request loop
check();
// if you want to cancel the request, just do request.abort();
});
此外,还有一个更高级的解决方案,使用 comet server 将数据从服务器推送到客户端,但在深入研究彗星之前,您应该先尝试使上述方法正常工作。如果您想阅读该主题,我建议您查看APE。