2013-07-10 164 views
-1

我正在使用jquery和javascript,用ajax调用来从json文件中获取所有信息。 json文件加载正常,并且完美地将点添加到地图中,但控制台中仍然存在错误。AJAX JSON解析返回false

"TypeError: obj[i].info is null" 

尽管每个点都正确插入并且内部有“info”属性,为什么jquery会给它一个空值?

示例代码:

$.ajax({ 
    url: 'http://localhost:3000/api/', 
    type: 'GET', 
    dataType: 'html', 
}).success(function(data){ 
    var obj = $.parseJSON(data); 
     console.log(obj); 
     $.each(obj, function(i, item){ 
      taxiData.push(new google.maps.LatLng(obj[i].info.latitude,obj[i].info.longitude)); 
     }); 

}).error(function(data){ 
    console.log("Error with data: " + data); 
}); 

我的JSON:

[{ 
     "id" : 1, 
     "ip" : "165.242.13.8", 
     "referer" : "www.facebook.com", 

     "info" : { 
      "request" : "165.242.13.8", 
      "ip" : "165.242.13.8", 
      "country_code2" : "JP", 
      "country_code3" : "JPN", 
      "country_name" : "Japan", 
      "continent_code" : "AS", 
      "region_name" : "11", 
      "city_name" : "Hiroshima", 
      "postal_code" : "", 
      "latitude" : 34.3963, 
      "longitude" : 132.45940000000002, 
      "dma_code" : null, 
      "area_code" : null, 
      "timezone" : "Asia/Tokyo" 
     } 
    } 
] 
+0

使用“数据类型: 'JSON', –

+0

我已经编辑我的代码,并设置数据类型为json,解析是正确的,但仍然存在错误 – Yagiz

+0

如果指定dataType,则不需要$ .parseJSON(data):json – LMeyer

回答

0

试试这个:

$.ajax({ 
    url : 'http://localhost:3000/api/', 
    type : 'GET', 
    dataType : 'json', 
}).success(function (data) { 
    var obj = data; 
    console.log(obj); 
    $.each(obj, function (i, item) { 
     var pushString = item.info.latitude + ',' + item.info.longitude; 
     var googleLatLong = new google.maps.LatLng(pushString); 
     taxiData.push(googleLatLong); 
    }); 
}).error(function (data) { 
    console.log("Error with data: " + data); 
}); 
2

您正在使用$.each错误。

each已经需要每个条目并将其作为条目提供给您。

使用:

$.each(obj, function(i, item){ 
      taxiData.push(new google.maps.LatLng(item.info.latitude,item.info.longitude)); 
     }); //Notice I don,t access the obj Object 
+0

它表示item [i]未定义 – Yagiz

+1

Item是您的对象数组,而不是数组本身 –

+0

我已将项目设置为taxiData.push(new google.maps.LatLng(item.info.latitude,item.info.longitude));但仍然错误继续,**但它打印点到屏幕** – Yagiz

0

首先, 可以设置

dataType : "json" 

,不要做

var obj = $.parseJSON(data); 

您的数据就已经是一个对象

硒condly, 此代码

console.log(obj); 
$.each(obj, function(i, item){ 
    console.log(obj[i].info.latitude); 
    console.log(obj[i].info.longitude); 
    console.log(item.info.latitude); 
    console.log(item.info.longitude); 
}); 

项目=== OBJ [I]