通过jQuery ajax成功的JSON响应循环



我如何循环通过json类型的响应?

在my 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);

In my index.php

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

请帮助。谢谢。

由于您使用的是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
    });
   }); 
});

最新更新