【问题标题】:jquery ajax array response handlingjquery ajax 数组响应处理
【发布时间】:2010-10-02 11:18:57
【问题描述】:

如何处理来自 .getjson 的数组响应。以下代码处理 ajax 请求。

function getinfo()
 {
     $query="select field_uname_value,field_uaddress_value,field_uphone_value from {content_type_udetails}";
     $result= db_query($query);
     $i=0;     
     while($item = db_fetch_object($result))
     {
      $info[$i++]=array($item->field_uname_value,$item->field_uaddress_value,$item->field_uphone_value);
     }
     print_r($info);
 }

并返回数组如下

Array
(
    [0] => Array
        (
            [0] => bharath
            [1] => 12th street ,ram nagar
            [2] => 213124442
        )

    [1] => Array
        (
            [0] => Christina
            [1] => 77,five corner
            [2] => 76874323
        )

    [2] => Array
        (
            [0] => Ranjan
            [1] => queen towers, 4th layout
            [2] => 45745747
        )

)

但以下 ajax 处理不起作用。如何获取数组响应

 $.getJSON('/knpgetuserinfo.json&timestamp'+new Date().getTime(), function(data) {
   alert(data[0][0]); 
}

【问题讨论】:

    标签: php jquery ajax arrays response


    【解决方案1】:

    你不能那样做,print_r 只是将数组打印成可读的文本,你仍然有一些键/值分离形式,当你使用getJSON 我会说你使用json_encode()

    function getinfo()
        {
            $query="select field_uname_value,field_uaddress_value,field_uphone_value from {content_type_udetails}";
             $result= db_query($query);
             $info = array();
             while($item = db_fetch_object($result))
             {
                 $info[] = array(
                     'name' => $item->field_uname_value,
                     'address' => $item->field_uaddress_value,
                     'phone' => $item->field_uphone_value
                 );
             }
             echo json_encode($info);
         }
    

    然后像这样使用javascript:

    $.getJSON('/knpgetuserinfo.json&timestamp'+new Date().getTime(), function(data) {
        $.each(data,function(item){
           //use item.name or item.address here
        });
    }
    

    【讨论】:

      【解决方案2】:

      您需要通过 json_encode 以 JSON 格式替换打印,而不是打印:

      print_r($info);
      

      与:

      echo json_encode($info);
      

      问题是您当前没有以JSON 格式返回数据,所以当 jQuery 进行解析时,它会失败。

      【讨论】:

      • json_encode 返回一个字符串,而不是 PHP 中任何类型的对象,应该只是回显!
      • @RobertPitt - 是的,当我在快速测试中拍打他的代码时,它提醒我,已经更新了:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-15
      • 2013-08-05
      • 1970-01-01
      相关资源
      最近更新 更多