【问题标题】:How to LOOP inside the Array returned from jQuery Ajax Success?如何在从 jQuery Ajax Success 返回的数组中循环?
【发布时间】:2014-05-19 08:58:00
【问题描述】:

我正在尝试循环从PHP 返回的数组。但是还是没办法。例子是~

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 ? -----

});

那我怎样才能知道我得到了哪些水果呢?

【问题讨论】:

    标签: javascript jquery ajax arrays


    【解决方案1】:

    你可以这样做:

    $.each(response.fruits,function(key,value){
    
    console.log(key+":"+value);
    
    });
    

    【讨论】:

      【解决方案2】:

      你可以使用$.each()函数来实现你想要的。

      试试,

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

      【讨论】:

        【解决方案3】:

        您可以使用$.each() 来迭代对象的属性,例如

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

        【讨论】:

          【解决方案4】:

          所有这些示例都使用jQuery,但您可以使用本机ECMA5 forEach。不需要图书馆!

          response.fruits.forEach(function(value){
              //do what you need to do
          });
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-10-09
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多