在jQuery中迭代json对象数组

时间:2016-09-26 10:04:39

标签: javascript php jquery json codeigniter

我正在使用CodeIgniter。在我的Controller文件中,我有一个包含数组的JSON(由于调用了不同的API')

{
    "Specialities": [{
        "SpecialityID": 1,
        "SpecialityName": "Eye Doctor"
    },{
        "SpecialityID": 2,
        "SpecialityName": "Chiropractor"
    },{
        "SpecialityID": 3,
        "SpecialityName": "Primary Care Doctor"
    }] 
}

在控制器中,我写了

echo $response[0];

使用这行代码,我可以轻松地遍历jquery中的json对象:

$.ajax({
    type: 'GET',
    url: 'http://localhost/rest_project/main/res',
    dataType: 'JSON',
    crossDomain: true,
    xhrFields: { withCredentials: true },
    success: function (data){
        $.each(data.Specialities,function(key,value){
            console.log(value.SpecialityName);
        });
    }  
});

但如果我传递数组:

echo json_encode($response); 

然后我无法得到结果:

$.ajax({
    type: 'GET',
    url: 'http://localhost/rest_project/main/res',
    dataType: 'JSON',
    crossDomain: true,
    xhrFields: { withCredentials: true },
    success: function (data){
        $.each(data[0].Specialities,function(key,value){
            console.log(value.SpecialityName);
        });
    }
});

有人能帮助我吗?

1 个答案:

答案 0 :(得分:2)

您的jsonObject似乎不是数组,而each仅适用于数组。

//Check if your jsonObject is array, if not then make it.
if (!$.isArray(jsonObject)) {
    jsonObject = [jsonObject];
}

$.each(jsonObject, function(key, value){
  console.log("FULL NAME " + value.FullName);
});



var data = {
    "Specialities": [{
        "SpecialityID": 1,
        "SpecialityName": "Eye Doctor"
    },{
        "SpecialityID": 2,
        "SpecialityName": "Chiropractor"
    },{
        "SpecialityID": 3,
        "SpecialityName": "Primary Care Doctor"
    }] 
};
//Convert your jsonObject to array for each
if (!$.isArray(data)) {
    data = [data];
}
$.each(data[0].Specialities,function(key,value){
   console.log(value.SpecialityName);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;