从MySQL数据库中使用Jquery,AJAX和PHP检索数据

cra*_*gtb 3 php mysql ajax jquery json

我试图弄清楚如何使用AJAX调用PHP页面从MySQL数据库中检索数据.我一直在关注这个教程

http://www.ryancoughlin.com/2008/11/04/use-jquery-to-submit-form/

但我无法弄清楚如何让它发送回json数据,以便我可以读取它.

现在我有这样的事情:

$('h1').click(function() {
            $.ajax({
                type:"POST",
                url: "ajax.php",
                data: "code="+ code,
                datatype: "xml",
                success: function() {

                $(xml).find('site').each(function(){
                    //do something
                });
            });


        });
Run Code Online (Sandbox Code Playgroud)

我想我的PHP会是这样的

    <?php

    include ("../../inc/config.inc.php");

    // CLIENT INFORMATION

    $code        = htmlspecialchars(trim($_POST['lname']));

    $addClient  = "select * from news where code=$code";
    mysql_query($addClient) or die(mysql_error());

?>
Run Code Online (Sandbox Code Playgroud)

本教程仅显示如何将数据插入表中,但我需要读取数据.有人能指出我的方向吗?

谢谢,

克雷格

mik*_*725 5

首先,我强烈建议在ajax请求中使用JS对象作为数据变量.当您拥有大量数据时,这将使您的生活变得更加简单.例如:

$('h1').click(function() {
            $.ajax({
                type:"POST",
                url: "ajax.php",
                data: { "code": code },
                datatype: "xml",
                success: function() {
                $(xml).find('site').each(function(){
                    //do something
                });
            });
        });
Run Code Online (Sandbox Code Playgroud)

至于从服务器获取信息,首先你必须制作一个PHP脚本来从数据库中提取数据.如果您想从服务器获取大量信息,那么您可能还想用XML或JSON序列化数据(我会推荐JSON).

在您的示例中,我将假设您的db表非常小而且简单.可用列是id,代码和说明.如果您想要提取特定代码的所有新闻描述,您的PHP可能如下所示.(我有一段时间没有做过任何PHP,所以语法可能有误)

// create data-structure to handle the db info
// this will also make your code more maintainable
// since OOP is, well just a good practice
class NewsDB {
    private $id = null;
    var $code = null;
    var $description = null;

    function setID($id) {
        $this->id = $id;
    }
    function setCode($code) {
        $this->code = $code;
    }
    function setDescription($desc) {
        $this->description = $desc;
    }
}

// now you want to get all the info from the db
$data_array = array(); // will store the array of the results
$data = null; // temporary var to store info to

// make sure to make this line MUCH more secure since this can allow SQL attacks
$code = htmlspecialchars(trim($_POST['lname']));

// query
$sql = "select * from news where code=$code";
$query = mysql_query(mysql_real_escape_string($sql)) or reportSQLerror($sql);

// get the data
while ($result = mysql_fetch_assoc($query)) {
    $data = new NewsDB();
    $data.setID($result['id']);
    $data.setCode($result['code']);
    $data.setDescription($result['description']);
    // append data to the array
    array_push($data_array, $data);
}

// at this point you got all the data into an array
// so you can return this to the client (in ajax request)
header('Content-type: application/json');
echo json_encode($data_array);
Run Code Online (Sandbox Code Playgroud)

样本输出:

[
  { "code": 5, "description": "desc of 5" },
  { "code": 6, "description": "desc of 6" },
  ...
]
Run Code Online (Sandbox Code Playgroud)

所以在这个阶段你将有一个PHP脚本,它返回JSON中的数据.还假设这个PHP脚本的URL是foo.php.

然后,您可以通过以下方式从服务器获取响应:

$('h1').click(function() {
            $.ajax({
                type:"POST",
                url: "foo.php",
                datatype: "json",
                success: function(data, textStatus, xhr) {
                   data = JSON.parse(xhr.responseText);
                   // do something with data
                   for (var i = 0, len = data.length; i < len; i++) {
                       var code = data[i].code;
                       var desc = data[i].description;
                       // do something
                   }
            });
         });
Run Code Online (Sandbox Code Playgroud)

就这样.