0

如何遍历 JSON 类型的响应?

在我的ajax_request.php

$json = '{

    "gallery": {
    "galleryName": "Gallery Name 1",
    "artist": "Artist 1",
    "description": "Description 1",
    "photos": {
        "photo" : {
            "location" : "location 1",
             "name"    : "name 1"
             
        } ,
        "photo" : {
            "location" : "location 1.2",
             "name"    : "name 1.2"
             
        }, 
        "photo" : {
            "location" : "location 1.3",
             "name"    : "name 1.3"
             
        }
    }
},

"gallery": {
    "galleryName": "Gallery Name 2",
    "artist": "Artist 2",
    "description": "Description 2",
    "photos": {
        "photo" : {
            "location" : "location 2.1",
             "name"    : "name 2.1"
             
        } ,
        "photo" : {
            "location" : "location 2.2",
             "name"    : "name 2.2"
             
        }, 
        "photo" : {
            "location" : "location 2.3",
             "name"    : "name 2.3"
             
        }
    }
}';
 echo json_encode($json);

在我的index.php

$.ajax({
    url: "ajax_request.php",
    dataType:"json", 
    type: "POST",
    success: function(data){
        //code here to loop
});

请帮忙。谢谢。

4

1 回答 1

1

由于您使用的是 jQuery,您可以使用 jquery 每个函数来循环 json

$.ajax({ url: "ajax_request.php", dataType:"json", type: "POST", success: function(data){
    $.each(data, function(key, value) {
       /// do stuff with key and value
    });
   }); 
});
于 2013-06-11T10:30:13.617 回答