使用jQuery通过JSON显示数据的最佳方法 [英] Best way to display data via JSON using jQuery

查看:176
本文介绍了使用jQuery通过JSON显示数据的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我知道我会包含一个.each来显示所有内容.

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

推荐答案

类似以下内容:

$.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");
          });
        });

将采用由产品键返回的PHP数组制成的json对象.例如:

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

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

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

And then call getJSON again with new parameters.

这篇关于使用jQuery通过JSON显示数据的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆