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

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

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

像这样的东西:

 $.getJSON("http://mywebsite.com/json/get.php?cid=15", function(data){ $.each(data.products, function(i,product){ content = '

' + product.product_title + '

'; content += '

' + product.product_short_description + '

'; content += ''; content += '
'; $(content).appendTo("#product_list"); }); });

将采用由产品密钥返回的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' ) ) ) 

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

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

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

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

完善! 谢谢Jay,下面是我的HTML:

     Facebook like ajax post - jQuery - ryancoughlin.com         

Check out the following posts:

我的JSON输出:

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

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

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

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

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