仅按键值显示JSon

时间:2017-11-24 10:25:54

标签: javascript html json ajax

我被ID拒绝渲染JSON数据,已经浏览了几篇文章但没有工作。

我有一个ajax电话:

$.ajax({
    url: '../../../get/api/city.json',
    dataType: 'json',
})
.done(function(data){
    console.log(data);
    var HTML = ''; 
        $.each(data.city, function(i,city){
        HTML += '<span>'+city.city_name+'</span>'; });

       $('#title').append(HTML);
    })
.fail(function(){
    alert('failed');
});

json输出是:

{"city":[
{"id":"4","year":"2014","city_name":"City A"},
{"id":"5","year":"2014","city_name":"City B"},
{"id":"6","year":"2014","city_name":"City C"}]}

我的情况我创建了一个html页面来呈现City A的信息,我想要的是过滤上面的JSON数据,只呈现来自城市A的信息。

非常感谢你们的帮助。 感谢

3 个答案:

答案 0 :(得分:1)

您可以在$.each添加过滤器,以检查城市ID是否是您想要的。

$.each(data.city, function (i, city) {
    if (city.id === 4)
        HTML += '<span>' + city.city_name + '</span>'; 
});

答案 1 :(得分:1)

可以准备一个包含所需城市名称的过滤器,并将其应用于您的数据阵列,以过滤您所提供的数据,如下所示:

var cities = {
  "city": [{
    "id": "4",
    "year": "2014",
    "city_name": "City A"
  }, {
    "id": "5",
    "year": "2014",
    "city_name": "City B"
  }, {
    "id": "6",
    "year": "2014",
    "city_name": "City C"
  }]
};

//Want only city with this name
var filter = "City A";

console.log(cities.city);

cities.city = cities.city.filter(function(obj) {
  return obj.city_name == filter;
});

console.log(cities.city);

答案 2 :(得分:1)

使用数组的filter()

尝试以下操作

var info = {"city":[
{"id":"4","year":"2014","city_name":"City A"},
{"id":"5","year":"2014","city_name":"City B"},
{"id":"6","year":"2014","city_name":"City C"}]};

var res = info.city.filter(function(item){
  return item.city_name =='City A';
});
console.log(res);
var HTML = '<span>'+res[0].city_name+'</span>';
$('#title').append(HTML)
HTML = '<span>'+res[0].id+'</span>';
$('#id').append(HTML);;
HTML = '<span>'+res[0].year+'</span>';
$('#year').append(HTML);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="title">Title: </div>
<div id="id">Id: </div>
<div id="year">Year: </div>

<强>更新 请求服务器发送数据后,您可以使用以下代码:

$.ajax({
  url: 'http://207.254.40.122/deetab/json.json',
  dataType: 'json',
  crossDomain: true
}).done(function(data){
    console.log(data);// Check here whether sever send data or not
    var res = data.city.filter(function(item){
       return item.city_name =='City A';
    });
   //console.log(res);
   var HTML = '<span>'+res[0].city_name+'</span>';
   $('#title').append(HTML)
   HTML = '<span>'+res[0].id+'</span>';
   $('#id').append(HTML);;
   HTML = '<span>'+res[0].year+'</span>';
   $('#year').append(HTML);
});