php - 如何将 json_encode 结果中的每个元素显示为 PHP 表格

标签 php jquery json

我想在 PHP 中将 json_encode 结果中的每个元素显示为表格格式(见下文)。在本例中,jQuery 代码(在 header 部分)和 PHP 代码(在正文部分)位于同一个 PHP 页面中。

有人可以帮助我吗?

+-------+-------+
|fruit  |price  |
+-------+-------+
|apple  |1.2    |
+-------+-------+
|pear   |1.5    |
+-------+-------+
|orange |1.0    |
+-------+-------+

test.php的结果:

[{"fruit":"apple","price":1.2},{"fruit":"pear","price":1.5},{"fruit":"orange","price":1.0}]

以上代码是test.php使用json_encode()的结果。

jQuery:

$(document).ready(function(){
                $.ajax({
                   type: "POST",
                   dataType:"Json",
                   url: "test.php",
                   success: function(result){


                   }
                 });
            });

最佳答案

您可以使用以下内容:

$(document).ready(function(){
var json_array = '';
$.ajax({
    type: "POST",
    dataType:"Json",
    url: "test.php",
    success: function(result){
        // Parse JSON
        var array_json = $.parseJSON(array_json);
        // We add each row in the table
        $.each(array_json, function(){
            $('#results').append('<tr><td>' + this.fruit + '</td><td>' + this.price + '</td></tr>');
        });
    }
});

});

使用以下 HTML:

<table id="results">
    <tr>
        <th>Fruit</th>
        <th>Price</th>
    </tr>
</table>

(根据您的 HTML 结构更改 ID)

关于php - 如何将 json_encode 结果中的每个元素显示为 PHP 表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8263084/

相关文章:

java - 无法将 java.util.ArrayList 的实例反序列化出 VALUE_STRING

python - Pandas 数据帧 : normalize one JSON column and merge with other columns

php - MySQL 与多个表的关系

javascript - 调整大小时 jQuery 轮播导航中断

javascript - 单击第一个 <td> 时展开表格行以显示更多内容

json - 如何解码转义的 JSON 字符串

php - 使用 jquery ajax 显示带有更新按钮的选定行表

php - 在 Prestashop 的注册表中添加地址字段

php - 如何在 python 中访问深层 JSON 属性

jquery - jquery中附加元素的间距不同