2014-10-09 65 views
0

因此让绝对的噩梦读取JSON回复 无论我做什么,我都会得到对象对象列表,未定义或其他问题,但我无法从JSON回复中获取实际信息,但是有一个JSON回复。我错过了什么。 的JSON调用如下Json数组只显示undefined undefined

var mapKeyUrl = "/GenMap/getcountry/jsonchk"; 
var mapKeyUrl = "/GenMap/getcountry/jsonchk" 
$.getJSON(mapKeyUrl, { 
    regsel: "${regsel}", 
    countryiso: code 
}) 
.done(function(contdata) { 
    alert(contdata) 
    contdata = contdata.country 
    alert(contdata) 
    document.getElementById("maptext").innerHTML = "I am an abwrock " + code + contdata.exturl; 
}) 

的响应(从铬调试拍摄)如下所示

{"country": 
    [ 
    {"ccode":["EG"]}, 
    {"cname":["Egypt"]}, 
    {"exturl":["N/A"]}, 
    {"impdate":[null]}, 
    {"lupdate":["2014-09-28T23:00:00Z"]}, 
    {"impnote":[null]} 
    ] 
} 

回答

2

你有一个数组,你没有考虑。您将需要访问您的数据,如下所示:

console.log(contdata); // would dump entire object 
console.log(contdata.country); // would dump inner array with length of 1 
console.log(contdata.country[0]); // would dump object inside array 
console.log(contdata.country[0].ccode[0]); // would dump country code 
+0

最终用contdata.country [0] .cname [0]得到了它。某些其他解决方案也适用,但这个最适合我。 – vrghost 2014-10-09 16:36:19

1

不管生成此相比似乎没有复杂的事项,并包裹了好几遍。

您需要做的是找到具有所需属性的对象(关键字),然后拉取该值,该值实际上是数组本身的值。

我会做什么是一样的东西:

var getProp = function(countryData, name) { 
    for(var i = 0; i < countryData.length; i++) { 
     if (countryData[i].hasOwnProperty(name)) { 
      var value_array = countryData[i][name]; 

      return value_array[0]; 
     } 
    } 

    return null; 
}; 

var code = getProp(contdata,"ccode"); 
var ext_url = getProp(contdata,"exturl"); 
+0

对不起,代码被定义在外面(应该有提到)。如何访问名为exturl的contdata数组内的对象。 – vrghost 2014-10-09 16:23:46

1

试试这个:

alert(JSON.stringify(contdata)); 

或使用

console.log(contdata); 

或使用

console.dir(contdata);