I'm trying to loop the returning Array from PHP
. But still don't get the way. Examples are ~
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: { "mand" : "getItems" }
}).success(function( response ) {
alert( response.fruits.apple ); //OK
// <------ here, how do i loop the response.fruits ? -----
});
Then how can i loop to know which Fruits i got, please?
I'm trying to loop the returning Array from PHP
. But still don't get the way. Examples are ~
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: { "mand" : "getItems" }
}).success(function( response ) {
alert( response.fruits.apple ); //OK
// <------ here, how do i loop the response.fruits ? -----
});
Then how can i loop to know which Fruits i got, please?
Share Improve this question edited May 19, 2014 at 9:03 Amal 76.7k18 gold badges132 silver badges153 bronze badges asked May 19, 2014 at 8:58 夏期劇場夏期劇場 18.4k46 gold badges141 silver badges226 bronze badges4 Answers
Reset to default 5you can do this way:
$.each(response.fruits,function(key,value){
console.log(key+":"+value);
});
You can use $.each()
function to achieve what you want.
Try,
$.each(response.fruits,function(key,val){
alert(key);
});
You can use $.each() to iterate over the properties of an object like
$.each(response.fruits, function(key,val){
console.log(key + '-' + val)
})
All these examples uses jQuery
, but you can do it with native ECMA5
forEach
. No library needed!
response.fruits.forEach(function(value){
//do what you need to do
});