2014-05-19 72 views
1

我想循環從PHP返回的數組。但仍然沒有辦法。例子是〜如何在從jQuery Ajax成功返回的數組中循環?

PHP:

$items = array(); 
$items["country"] = "North Korea", 
$items["fruits"] = array(
         "apple"=>1.0, 
         "banana"=>1.2, 
         "cranberry"=>2.0, 
        ); 
echo json_encode($fruits); 

的jQuery:

$.ajax({ 
    url: "items.php", 
    async: false, 
    type: "POST", 
    dataType: "JSON", 
    data: { "command" : "getItems" } 
}).success(function(response) { 

    alert(response.fruits.apple); //OK 
    // <------ here, how do i loop the response.fruits ? ----- 

}); 

那我怎麼才能循環知道我有哪些水果嗎?

回答

5

你可以做到這樣:

$.each(response.fruits,function(key,value){ 

console.log(key+":"+value); 

}); 
2

可以使用$.each()函數來實現你想要什麼。

嘗試,

$.each(response.fruits,function(key,val){ 
    alert(key); 
}); 
2

您可以使用$.each()來遍歷一個對象的屬性,如

$.each(response.fruits, function(key,val){ 
    console.log(key + '-' + val) 
}) 
1

所有這些例子使用jQuery,但您可以用本地ECMA5forEach做到這一點。沒有圖書館需要!

response.fruits.forEach(function(value){ 
    //do what you need to do 
});