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: { "command" : "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?
you 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
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.