为什么我的json数据没有从jquery的每个循环中获取?

时间:2014-09-25 11:48:25

标签: javascript jquery ajax json

我有一组数据是从已经解析了json数据的url创建/提取的,如下所示:

[
{
"id": 1,
"school_name": "another school in essex",
"website": null,
"book_id": 27,
"url": "http://localhost:3000/schools/1.json"
},
{
"id": 2,
"school_name": "ddffdfd",
"website": null,
"book_id": 31,
"url": "http://localhost:3000/schools/2.json"
},
{
"id": 3,
"school_name": "ddfdfdffd",
"website": null,
"book_id": 31,
"url": "http://localhost:3000/schools/3.json"
},
{
"id": 4,
"school_name": "4545455454",
"website": null,
"book_id": 31,
"url": "http://localhost:3000/schools/4.json"
}
]

我有一个.each循环,它抓取数据并将其分配给(city)参数,这样我就可以抓住那个城市参数并循环,然后从json out put and use中获取我想要的东西。

var info = '/schools.json';

$.get(info, function(response) {
  var jsonData = response
  var mapContent = $('').html();
  var json = jsonData;
}

function setMarkers(map, json) {
  jQuery.each(json, function (index, city) {
     console.log(city[id]);
   }
}

当我尝试访问上面.each循环中的json对象时,它什么都没有。如何从每个json输出中访问id?

干杯

3 个答案:

答案 0 :(得分:1)

试试这个,你没有调用setMarkers函数,也没有关闭$ .get函数。此外,当您从对象获取值时,您应该使用obj ['value']或obj.value

var info = '/schools.json';

$.get(info, {}, function(response) {
  var mapContent = $('').html();
  setMarkers(mapContent, response);
}, 'json');

function setMarkers(map, json) {
  jQuery.each(json, function (index, city) {
     console.log(city['id']);
   }
}

答案 1 :(得分:0)

$.get(info,PARAMS, function(response) {
    var jsonData = response
    var mapContent = $('').html();
    var json = jsonData;
},"json");

我想你忘记了结束')'和一个功能参数:' PARAMS'可以为null 试着添加" json"作为最后的论点。

希望有所帮助

答案 2 :(得分:0)

您的代码应返回ReferenceEerror: id is not defined。请改用city["id"]city.id

并检查json是否是有效的json对象,而不是字符串