json对象数组未定义错误

时间:2014-10-22 18:16:08

标签: javascript jquery ajax json

我有一个JSON对象,它由AJAX请求返回,但它一直返回undefined。

{
"shelters": [{
    "id": 1,
    "name": "ksk",
    "introduce": "설정에서 변경해주세요",
    "lonlat": "lon=14135650.08512,lat=4518305.530134",
    "created_at": "2014-10-21T11:30:34.916Z",
    "updated_at": "2014-10-21T12:16:24.943Z"
}, {
    "id": 2,
    "name": "aa",
    "introduce": "설정에서 변경해주세요",
    "lonlat": "lon=14135014.702323,lat=4518095.3283062",
    "created_at": "2014-10-22T16:52:03.912Z",
    "updated_at": "2014-10-22T16:53:07.407Z"
}]
}    
alert(data.length);
alert(data.shelters.length);
alert(data.shelters);

为什么输出'未定义'?

2 个答案:

答案 0 :(得分:0)

尝试这样的事情:

var myJson= JSON.parse('{"shelters":[{"id":1,"name":"ksk","introduce":"설정에서 변경해주세요","lonlat":"lon=14135650.08512,lat=4518305.530134","created_at":"2014-10-21T11:30:34.916Z","updated_at":"2014-10-21T12:16:24.943Z"},{"id":2,"name":"aa","introduce":"설정에서 변경해주세요","lonlat":"lon=14135014.702323,lat=4518095.3283062","created_at":"2014-10-22T16:52:03.912Z","updated_at":"2014-10-22T16:53:07.407Z"}]}');

console.log(myJson.shelters[0]);

工作小提琴:http://jsfiddle.net/robertrozas/kv9fv3jp/1/

答案 1 :(得分:0)

我认为您需要使用jQuery.getJSON()代替jQuery.ajax()