使用 jQuery 通过 JSON 显示数据的最佳方式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/327231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 08:57:43  来源:igfitidea点击:

Best way to display data via JSON using jQuery

jqueryjson

提问by Coughlin

i am trying to find the best way to display results on my page via an Ajax call using jQuery, do you think the best way is to pass it as JSON or plain text? I have worked with ajax calls before, but not sure which is preferred over the other and for the JSON version what is the best way to read from a JSON file generated by a PHP page to display my results.

我正在尝试找到通过使用 jQuery 的 Ajax 调用在我的页面上显示结果的最佳方式,您认为最好的方式是将其作为 JSON 还是纯文本传递?我以前使用过 ajax 调用,但不确定哪个优先于另一个,对于 JSON 版本,从 PHP 页面生成的 JSON 文件中读取以显示我的结果的最佳方式是什么。

i know I would include a .eachto run through it to display them all.

我知道我会包含一个.each来运行它以显示它们。

回答by Jay

Something like this:

像这样的东西:

$.getJSON("http://mywebsite.com/json/get.php?cid=15",
        function(data){
          $.each(data.products, function(i,product){
            content = '<p>' + product.product_title + '</p>';
            content += '<p>' + product.product_short_description + '</p>';
            content += '<img src="' + product.product_thumbnail_src + '"/>';
            content += '<br/>';
            $(content).appendTo("#product_list");
          });
        });

Would take a json object made from a PHP array returned with the key of products. e.g:

将采用一个由 PHP 数组制成的 json 对象,该数组与产品的键一起返回。例如:

Array('products' => Array(0 => Array('product_title' => 'Product 1',
                                     'product_short_description' => 'Product 1 is a useful product',
                                     'product_thumbnail_src' => '/images/15/1.jpg'
                                    )
                          1 => Array('product_title' => 'Product 2',
                                     'product_short_description' => 'Product 2 is a not so useful product',
                                     'product_thumbnail_src' => '/images/15/2.jpg'
                                    )
                         )
     )

To reload the list you would simply do:

要重新加载列表,您只需执行以下操作:

$("#product_list").empty();

And then call getJSON again with new parameters.

然后使用新参数再次调用 getJSON。

回答by braindead

JQuery has an inbuilt json data type for Ajax and converts the data into a object. PHP% also has inbuilt json_encode function which converts an array into json formatted string. Saves a lot of parsing, decoding effort.

JQuery 具有用于 Ajax 的内置 json 数据类型,并将数据转换为对象。PHP% 还具有内置的 json_encode 函数,可将数组转换为 json 格式的字符串。节省了大量的解析、解码工作。

回答by Coughlin

Perfect! Thank you Jay, below is my HTML:

完美的!谢谢杰,下面是我的 HTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Facebook like ajax post - jQuery - ryancoughlin.com</title>
<link rel="stylesheet" href="../css/screen.css" type="text/css" media="screen, projection" />
<link rel="stylesheet" href="../css/print.css" type="text/css" media="print" />
<!--[if IE]><link rel="stylesheet" href="../css/ie.css" type="text/css" media="screen, projection"><![endif]-->
<link href="../css/highlight.css" rel="stylesheet" type="text/css" media="screen" />
<script src="js/jquery.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
/* <![CDATA[ */
$(document).ready(function(){
    $.getJSON("readJSON.php",function(data){
        $.each(data.post, function(i,post){
            content += '<p>' + post.post_author + '</p>';
            content += '<p>' + post.post_content + '</p>';
            content += '<p' + post.date + '</p>';
            content += '<br/>';
            $(content).appendTo("#posts");
        });
    });   
});
/* ]]> */
</script>
</head>
<body>
        <div class="container">
                <div class="span-24">
                       <h2>Check out the following posts:</h2>
                        <div id="posts">
                        </di>
                </div>
        </div>
</body>
</html>

And my JSON outputs:

我的 JSON 输出:

{ posts: [{"id":"1","date_added":"0001-02-22 00:00:00","post_content":"This is a post","author":"Ryan Coughlin"}]}

I get this error, when I run my code:

当我运行我的代码时,我收到此错误:

object is undefined
http://localhost:8888/rks/post/js/jquery.js
Line 19

回答by strager

You can create a jQuery object from a JSON object:

您可以从 JSON 对象创建一个 jQuery 对象:

$.getJSON(url, data, function(json) {
    $(json).each(function() {
        /* YOUR CODE HERE */
    });
});