1

我正在向外部 php 文件发出 ajax 请求,然后返回一些 json。大多数 json 都是直截了当的,但我似乎无法弄清楚如何解析多维部分。


JSON:

{
    "success":"TRUE",
    "action":"JSON",
    "date":"06/29/12",
    "results":"true",
    "numResults":2,
    "0":[
        "id":1234,
        "name":"John Appleseed",
        "gender":"male",
        "average":2.5
    ],
    "1":[
        "id":5678,
        "name":"Jessica Smith",
        "gender":"female",
        "average":1.4
    ]
}

jQuery:

$.ajax({
url: "searchController.php",
data: searchData,
type: "GET",
success:function(q) {
    if (q) { // Results
        $('#search .container .body .ajax .returnedHTML .loadingScreen').hide();                                
        var json = $.parseJSON(q);
        console.log(json);
        if (json.success == "true") {
            var numResults = json.numResults;
            if (numResults == 1) {
            $('#search .container .body .ajax .returnedHTML .content').contents().remove();
            var htmlString = '<div class="searchContent"><ul><li class="returnedResults '+json.type+'"><a href="/#!/'+json.type+'/'+json.id+'/"><div class="title">'+json.name+'</div><div class="body"><div class="quickview"><ul><li><div class="average">'+json.average+'</div><br><span>Average</span></li><li><div class="rates">'+json.numrates+'</div><br><span>Rates</span></li><li><div class="followers">'+json.followers+'</div><br><span>Followers</span></li></ul></div></div></a></li></ul></div>';
            $('#search .container .body .ajax .returnedHTML .content').append(htmlString);
            console.log(htmlString);                                          
        }
    }
});

如何解析 JSON,以便我可以访问所有数据,而不仅仅是第一维中的数据?我在这个网站上环顾四周,找不到任何有用和/或有用的东西。非常感谢!

4

3 回答 3

2

您的阵列位于json[0]json[1]

 ...
for(var i in json) {
  if(!isNaN(i)) {
    ...
    refer to you variables as json[i].name, json[i].average, etc.
    ...
  }
}                                  
于 2012-06-29T07:11:36.707 回答
1
$.ajax({
url: "searchController.php",
data: searchData,
type: "GET",
success:function(q) {
    if (q) { // Results
        $('#search .container .body .ajax .returnedHTML .loadingScreen').hide();                                
        var json = $.parseJSON(q);
        console.log(json);
        if (json.success.toLowerCase() == "true") {
            ...                                  
        }
    }
});


for(var key in json){
    if(json.hasOwnProperty(key){
       console.log(key);
       console.log(json[key]);
    }    
}
于 2012-06-29T07:20:16.377 回答
0

关于您的 JSON,您必须再次解析相同的内容,

var jsonArr1 = $.parseJSON(json.0);
var jsonArr2 = $.parseJSON(json.1);
于 2012-06-29T07:10:24.263 回答