我的 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');
}
});
效果很好,但我想将其更改为仅显示德国商店(或用户选择的商店)。
最佳答案
检查您要过滤到的国家/地区,仅在与当前地点匹配时才附加它。
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');
}
关于jquery - 使用 jQuery 从 json 中仅获取一些元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33897333/