已经提到过两次了,但我仍然想强调它。你永远不会希望客户端能够直接访问数据库。这是一个严重的安全风险。
现在来解决。首先,你会想建立一个PHP文件,你可以用ajax来请求。让我们把这种check.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调用的状态,如果它已经完成或没有。因此,如果服务器出现问题,您可能会收到堆叠请求,但这并不好。
因此,为了防止这种情况,我们改用success -callback的AJAX方法的组合(.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。