最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to LOOP inside the Array returned from jQuery Ajax Success? - Stack Overflow

programmeradmin3浏览0评论

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 badges
Add a ment  | 

4 Answers 4

Reset to default 5

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
});
发布评论

评论列表(0)

  1. 暂无评论