Json只显示具有特定id的对象

时间:2012-05-28 01:48:25

标签: jquery json

我想知道如何将具有特定id的json对象打印到div?! 我的json文件看起来像这样(缩短),并由我使用的网店程序自动生成:

 "shipping":{
   "methods":{
     "core|13490|40699":{
       "id":"core|13490|40699",
       "price":{
         "price_excl":"0.0000","price_incl":"0.0000"
       }
     },
     "core|10292|40695":{
       "id":"core|10292|40695",
       "price":{
         "price_excl":"21.0084","price_incl":"25.0000"
       }
     }
   }
 },

和我的脚本一样:

        window.onload = function(){
      $.getJSON('http://shop.com/cart/?format=json', function(data){
        $.each(data.cart.shipping.methods, function(index, method){
          $('<span></span>')
            .html('<strong>' + method.price.price_incl + '</strong>')
            .appendTo('.cart-shipping');
        });
      });
    };

我试图表示只显示ID为“core | 10292 | 40695”的运输方式的运费。使用代码我会显示两个运费。此外,我想知道如何将这些价格格式化为“实际”价格而不是25.000。

我对JSON,jquery / ajax很新,你可能会看到,但我愿意学习。上面我找到了搜索这个网站,但我的问题是我真的无法弄清楚的。

3 个答案:

答案 0 :(得分:1)

您是否尝试使用简单的if语句?例如:

if (index == "core|10292|40695") {
    $('<span></span>').html('<strong>' + method.price.price_incl + '</strong>').appendTo('.cart-shipping');
}

关于格式化货币,我确信有plenty of information available

答案 1 :(得分:1)

您要做的是替换以下块:

$.each(data.cart.shipping.methods, function(index, method){
  $('<span></span>').html('<strong>' + method.price.price_incl + '</strong>').appendTo('.cart-shipping');
});

使用:

$('<span></span>').html('<strong>' + data.cart.shipping.methods['core|10292|40695'].price.price_incl + '</strong>').appendTo('.cart-shipping');

基本上,原始代码使用$ .each构造通过接收的数据进行迭代。在您的情况下,您不希望通过所有值进行迭代,您已经知道您想要哪一个。

另外,请注意建议您使用if语句的答案。这些答案仍将通过整个对象进行迭代,浪费资源。

答案 2 :(得分:-1)

$('<span></span>').html("whatever")将创建包含此类数据的范围,但页面上尚未显示范围。

尝试在页面上放置一个容器并在其中插入数据。

例如

HTML: <div id="a"></div>

JS: <script>$('#a').html('test');</script>