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

3
我正在努力弄清楚如何使用 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
                });
            });


        });

我猜我的 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());

?>

这个教程只展示了如何向表中插入数据,但我需要读取数据。有人能指点一下吗?

谢谢,

Craig


刚刚更新了答案。现在应该更清晰了。 - miki725
2个回答

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
                });
            });
        });

关于从服务器获取信息,首先您需要编写一个PHP脚本来从数据库中提取数据。如果您要从服务器获取大量信息,则还可以将数据序列化为XML或JSON格式(我建议使用JSON)。

在您的示例中,我假设您的数据库表非常小且简单。可用列为id、code和description。如果您想为特定代码获取所有新闻描述,则您的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);

示例输出:
[
  { "code": 5, "description": "desc of 5" },
  { "code": 6, "description": "desc of 6" },
  ...
]

现在,您应该拥有一个返回JSON数据的PHP脚本。假设这个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
                   }
            });
         });

这就是全部。


我如何从php获取实时输出?事实上,我的php脚本运行了10分钟左右,并且每2分钟就会输出一些内容。我想捕获这些输出并在html中使其可用,而不是等待php脚本的完整执行。@miki725有任何线索吗? - Govind Kailas
太棒了,谢谢你的回答!虽然其中有一些Java风格,但并不是很重要。现在一切都像应该的那样工作了。你真是个牛人! - Sindri Þór
@miki725 你好,可以帮我回答一下这个问题吗?https://dev59.com/spbfa4cB1Zd3GeqPr1Gk 我对ajax很迷茫。 - Maduro

4

2
嘿,http://openenergymonitor.org/emon/node/107 教程似乎是我想要的,但它只输出了第一行数据。你有什么办法可以让其他行也打印出来吗? - craigtb
1
在 client.php 文件中检查 var id = data[0]; var vname = data[1]; 这段代码。这可能是文章示例,仅返回单行数据。在此处进行操作以获取所有数据。 - user319198
1
在api.php中执行类似以下代码: while($row = mysql_fetch_row($result)){ $table_data[]= array("id=>"$row['id'],name=>$row['name']); } echo json_encode($table_data); - user319198

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接