为什么无法显示getJSON传递的数据?

问题描述 投票:1回答:2

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 | [email protected] |59.51.24.37
welcome2 | welcome2  | welcome2 | [email protected] |59.51.24.38

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

[ {title:"welcome1",
         content:"welcome1",
        author:"welcome1",
         email:"[email protected]",
        ip:"59.51.24.37"},
{title:"welcome2",
         content:"welcome2",
        author:"welcome2",
         email:"[email protected]",
        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  [email protected]  59.51.24.37
welcome2  welcome2  welcome2  [email protected]  59.51.24.38
javascript json ajax getjson
2个回答
1
投票

问题是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": "[email protected]",
    "ip": "59.51.24.37"
  },
  {
    "title": "welcome2",
    "content": "welcome2",
    "author": "welcome2",
    "email": "[email protected]",
    "ip": "59.51.24.38"
  }
]

1
投票

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

以下是服务器端应该处理的事情(PHP):

文件名:test-json.php

  1. 从数据库中获取记录。
  2. 使用已从数据库中提取的记录填充数组(我在下面的代码中将该数组命名为$data)。
  3. 将该数组编码为JSON格式并回显结果。

以下是客户端(JavaScript)应该如何处理的事情:

  1. AJAX文件发出test-json.php请求。
  2. 如果该请求成功,则迭代返回的JSON并填充一个变量(我将其命名为'html'),该变量将保存将附加到表中的所有HTML代码(以及接收的数据)。
  3. 将该变量(我命名为'html')附加到表中,我们获得了性能,因为我们每DOM请求只访问AJAX一次。

尽管如此,这是解决方案:

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

Learn more关于json_encode功能。

希望我进一步推动你。

© www.soinside.com 2019 - 2024. All rights reserved.