繁体   English   中英

为什么不能显示通过getJSON传递的数据?

[英]Why can't show data passed by getJSON?

test-json.php读取数据库,并以JSON格式准备它。

<?php
$conn = new mysqli("localhost", "root", "xxxx", "guestbook"); 
$result=$conn->query("select * From lyb limit 2"); 
echo '[';
$i=0;
while($row=$result->fetch_assoc()){  ?>
 {title:"<?= $row['title'] ?>",
        content:"<?= $row['content'] ?>",
        author:"<?= $row['author'] ?>",
        email:"<?= $row['email'] ?>",
        ip:"<?= $row['ip'] ?>"}
<?php 
if(
$result->num_rows!=++$i) echo ',';   
}
echo ']'    
?>

对于我的数据库, select * From lib limit 2获取记录。

title    | content   | author   | email            |ip
welcome1 | welcome1  | welcome1 | welcome1@tom.com |59.51.24.37
welcome2 | welcome2  | welcome2 | welcome2@tom.com |59.51.24.38

php -f /var/www/html/test-json.php

[ {title:"welcome1",
         content:"welcome1",
        author:"welcome1",
         email:"welcome1@tom.com",
        ip:"59.51.24.37"},
{title:"welcome2",
         content:"welcome2",
        author:"welcome2",
         email:"welcome2@tom.com",
        ip:"59.51.24.38"}]

test-json.php以JSON格式获取一些数据。

现在回调数据并将其显示在表中。

<script src="http://127.0.0.1/jquery-3.3.1.min.js"></script>
<h2 align="center">Ajax show data in table</h2>
<table>
    <tbody id="disp">
        <th>title</th>
        <th>content</th>
        <th>author</th>
        <th>email</th>
        <th>ip</th>
    </tbody>
</table>

<script> 
$(function(){
    $.getJSON("test-json.php", function(data) {
        $.each(data,function(i,item){
            var tr = "<tr><td>" + item.title + "</td>"    +
                        "<td>"  + item.content  + "</td>" +
                        "<td>"  + item.author  + "</td>"  +
                        "<td>"  + item.email  + "</td>"   +
                        "<td>"  + item.ip  + "</td></tr>"
            $("#disp").append(tr);
        });
    });
});
</script>

输入127.0.0.1/test-json.html ,为什么网页上没有test-json.php创建的数据?

我得到的如下:

Ajax show data in table
title   content author  email   ip

我期望如下:

Ajax show data in table
title   content author  email   ip
welcome1  welcome1  welcome1  welcome1@tom.com  59.51.24.37
welcome2  welcome2  welcome2  welcome2@tom.com  59.51.24.38

问题是来自您的PHP脚本的响应是无效的JSON。

在JSON中,对象键必须加引号。

与其尝试自己动手做JSON响应,不如使用json_encode()为您完成它。 例如

<?php
$conn = new mysqli("localhost", "root", "xxxx", "guestbook"); 
$stmt = $conn->prepare('SELECT title, content, author, email, ip FROM lyb limit 2');
$stmt->execute();
$stmt->bind_result($title, $content, $author, $email, $ip);
$result = [];
while ($stmt->fetch()) {
    $result[] = [
        'title'   => $title,
        'content' => $content,
        'author'  => $author,
        'email'   => $email,
        'ip'      => $ip
    ];
}
header('Content-type: application/json; charset=utf-8');
echo json_encode($result);
exit;

您不必使用prepare()bind_result() ,这只是我在使用MySQLi时的偏好。

这将产生类似

[
  {
    "title": "welcome1",
    "content": "welcome1",
    "author": "welcome1",
    "email": "welcome1@tom.com",
    "ip": "59.51.24.37"
  },
  {
    "title": "welcome2",
    "content": "welcome2",
    "author": "welcome2",
    "email": "welcome2@tom.com",
    "ip": "59.51.24.38"
  }
]

您的PHP代码中有很多错误。

这是应该在服务器端( PHP )中处理的事情:

文件名: test-json.php

  1. 从数据库中获取记录。

  2. 使用已经从数据库中获取的记录填充一个数组(在下面的代码中,我将该数组命名为$data )。

  3. 将该数组编码为JSON格式,然后回显结果。

这是应该在客户端( JavaScript )中处理事情的方式:

  1. test-json.php文件发出AJAX请求。

  2. 如果该请求成功,则遍历返回的JSON并填充一个变量(我将其命名为“ html”),该变量将保存将附加到表的所有HTML代码(以及接收到的数据)。

  3. 将变量(我命名为“ html”)添加到表中,这样就可以提高性能,因为每个AJAX请求仅访问一次DOM

话虽如此,以下是解决方案:

PHP代码-文件名: test-json.php

<?php
// use the column names in the 'SELECT' query to gain performance against the wildcard('*').
$conn = new MySQLi("localhost", "root", "xxxx", "guestbook"); 

$result = $conn->query("SELECT `title`, `content`, `author`, `email`, `ip` FROM `lyb` limit 2"); 

// $data variable will hold the returned records from the database.
$data = [];

// populate $data variable.
// the '[]' notation(empty brackets) means that the index of the array is automatically incremented on each iteration.
while($row = $result->fetch_assoc()) {
  $data[] = [
    'title'   => $row['title'],
    'content' => $row['content'],
    'author'  => $row['author'],
    'email'   => $row['email'],
    'ip'      => $row['ip']
  ];
}

// convert the $data variable to JSON and echo it to the browser.
header('Content-type: application/json; charset=utf-8');
echo json_encode($data);

JavaScript代码

$(function(){
    $.getJSON("test-json.php", function(data) {
        var html = '';
        $.each(data,function(key, value){
            html += "<tr><td>" + value.title + "</td>"    +
                        "<td>"  + value.content  + "</td>" +
                        "<td>"  + value.author  + "</td>"  +
                        "<td>"  + value.email  + "</td>"   +
                        "<td>"  + value.ip  + "</td></tr>";

        });
        $("#disp").append(html);
    });
});

了解有关json_encode函数的更多信息。

希望我能进一步推动您。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM