JSON未定义的节点试图解析

时间:2016-03-21 00:13:49

标签: javascript json

当我尝试访问其中一个节点时,尝试解析JSON并获取UNDEFINED。 JSON的第一部分和函数在

下面
function loadmakes()
    {

    jQuery.ajax({
    url: "getedmunds.php",
    data:'id=1',
    type: "POST",
    success:function(data){
        alert( data);       
        alert(data.makes); //<<<< **FAILS HERE Undefined** 

        for(var i in data.makes)
                {
                         $('#make').append('<option value=' + data.makes[i].id + '>' + data.makes[i].name + '</option>');
                }
    }, 
    error:function (){
        alert("Error calling makes");
        }
    });

}

这是JSON的第一行

{"makes":[{"id":200002038,"name":"Acura","niceName":"acura","models":[{"id":"Acura_ILX","name":"ILX","niceName":"ilx","years":[{"id":200471908,"year":2014}]},{"id":"Acura_ILX_Hybrid","name":"ILX Hybrid","niceName":"ilx-hybrid","years":[{"id":200493809,"year":2014}]},{"id":"Acura_MDX","name":"MDX","niceName":"mdx","years":[{"id":200465929,"year":2014}]},{"id":"Acura_RDX","name":"RDX","niceName":"rdx","years":[{"id":200467168,"year":2014}]},{"id":"Acura_RLX","name":"RLX","niceName":"rlx","years":[{"id":100539511,"year":2014}]},{"id":"Acura_TL","name":"TL","niceName":"tl","years":[{"id":200488448,"year":2014}]},{"id":"Acura_TSX","name":"TSX","niceName":"tsx","years":[{"id":200490517,"year":2014}]},{"id":"Acura_TSX_Sport_Wagon","name":"TSX Sport Wagon","niceName":"tsx-sport-wagon","years":[{"id":200673755,"year":2014}]}]},{"id":200001769,"name":"Aston Martin","niceName":"aston-martin","models":[{"id":"Aston_Martin_DB9","name":"DB9","niceName":"db9","years":[{"id":200473436,"year":2014}]},...

1 个答案:

答案 0 :(得分:1)

问题是data不是解析的JSON对象,它是一个字符串。当您使用AJAX时,它会返回一个字符串。

你可以做以下两件事之一:一,jQuery提供dataType option for $.ajax。只需提供值"json",jQuery / AJAX将自动为您解析结果。

$.ajax({
    // ...
    dataType: 'json',
    success: function(data) {
        // `data` is a javascript object now.
    }
});

您还可以使用JSON.parse成功解析data。这实际上是jQuery / AJAX通过最后的解决方案为你做的。