使用jQuery从json中只获取一些元素

时间:2015-11-24 15:17:50

标签: jquery json ajax

我有json就是这样(摘录):

[  
   {  
      "country":"Germany",
      "name":"Blabla",
      "address":"gsdfs",
      "address2":"",
      "city":"London",
      "state":"",
      "postal":"00100",
      "phone":"+2383 232",
      "email":"email@domain.com"
   },
   {  
      "country":"Germany",
      "name":"Blabla",
      "address":"gsdfs",
      "address2":"",
      "city":"London",
      "state":"",
      "postal":"90400",
      "phone":"+2383 232",
      "email":"email@domain.com"
   },
   {  
      "country":"United Kingdom",
      "name":"Blabla London",
      "address":"gsdfs",
      "address2":"",
      "city":"London",
      "state":"",
      "postal":"2984B746",
      "phone":"+2383 232",
      "email":"email@domain.com"
   },
   {  
      "country":"Japan",
      "name":"Blabla Tokyo",
      "address":"gsdfs",
      "address2":"",
      "city":"London",
      "state":"",
      "postal":"3455",
      "phone":"+2383 232",
      "email":"email@domain.com"
   }
]

现在我想只获得某个国家/地区的商品。例如,用户单击元素,表示获取所有德语地址,因此我将获取json,然后仅打印德国的那些。

我现在的jQuery就像这样(只打印所有地址):

 $.ajax({
    type: 'POST', 
    url: 'http://example/address.json',
    dataType: 'json',
    success: function (data) {
        $.each(data, function(index, place) {
            places =
                "<ul>"
                    + "<li>"
                    + place.name
                    + "</strong></li>"
                    + "<li>"
                    + place.postal
                    + " "
                    + place.city
                    + "</li>"                               + "</ul>";
            $('#placesContainer').append(places);
        });
        console.log('ajax success');
    },
    error: function (request, textStatus, errorThrown) {
        console.log('ajax error');
    }
});  

哪个效果很好,但我想改变它只展示德国商店(或用户选择的东西)。

1 个答案:

答案 0 :(得分:4)

检查您要过滤的国家/地区,只有在与当前位置匹配时才附加。

var country = "Germany";
...

success: function (data) {
    $.each(data, function(index, place) {
        if(place.country == country) {
            places =
                "<ul>"
                    + "<li>"
                    + place.name
                    + "</strong></li>"
                    + "<li>"
                    + place.postal
                    + " "
                    + place.city
                    + "</li>"                               + "</ul>";
            $('#placesContainer').append(places);
        }
    });
    console.log('ajax success');
}