1

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?

4 Answers 4

5

you can do this way:

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

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

});
Sign up to request clarification or add additional context in comments.

Comments

2

You can use $.each() function to achieve what you want.

Try,

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

Comments

2

You can use $.each() to iterate over the properties of an object like

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

Comments

1

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
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.