2011-01-13 124 views
0

我想从mySQL中获取一些数据,而无需使用jQuery刷新页面。有人可以告诉我如何获取数据,如果任何记录在MySQL表中更新。例如,以下代码从数据库中提取数字计数,如果有人在数据库中添加一个数字并更新数字,我如何在不刷新页面的情况下显示新数字?谢谢。从jQuery获取mysql数据

<? 
$query = "SELECT number, name FROM members WHERE id=1"; 
$result = mysql_query($query); 

$row = mysql_fetch_array($result); 
$number = $row['number']; ?> 
+3

你不想直接这样做。您想使用jQuery向PHP脚本发出Ajax请求,然后发出数据库请求。 JQuery Ajax文档:http://api.jquery.com/jQuery.ajax/ – 2011-01-13 23:52:12

回答

3

已经提到过两次了,但我仍然想强调它。你永远不会希望客户端能够直接访问数据库。这是一个严重的安全风险。

现在来解决。首先,你会想建立一个PHP文件,你可以用ajax来请求。让我们把这种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调用的状态,如果它已经完成或没有。因此,如果服务器出现问题,您可能会收到堆叠请求,但这并不好。

因此,为了防止这种情况,我们改用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

0

正如@Pekka提到的,您需要对调用db调用的PHP页面进行AJAX调用。然而,看起来你的问题比这更复杂一点,因为当插入新记录时,你想定期检查并更新(你的页面的一部分?),对吧?

如果是这样,你应该能够使用setInterval()来做到这一点。这是一个原生的javascript函数,基本上只是设置一个间隔(以毫秒为单位),然后运行一些代码。 setInterval()setTimeout()不同的是setInterval()重复运行,直到您告诉它停止(使用clearInterval())。

因此,您可以使用它每隔30秒(或任何您喜欢的)进行AJAX调用以查找新记录并相应地更新结果div。

+0

请不要宽恕`setInterval()`的用法。这是一个非常糟糕的做法!我将展示一个更好的解决方案。 – mekwall 2011-01-14 00:13:38

+0

setInterval具有正数和负数,其他选项(如长轮询)也如此。如果不了解更多关于OP的设置,我不会直接驳斥它。 – zaius 2011-01-14 00:32:43