2014-05-19 112 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 
});