如何在jquery中的arrray中访问stdclass对象

时间:2016-04-11 08:55:18

标签: php jquery codeigniter

我在codeignitor中有一个模型函数

     public function show_list()
{

    $query = $this->db->get('area_list');
    $area_list = $query->result();

    return $area_list;
}

然后我在控制器中有一个函数来使用模型的功能

     public function showarea()
{

    $area_list = $this->area_model->show_list();
    $data = [];
    foreach ( $area_list as $area ) {
        $data[] = $area;
    }
    echo json_encode($data);

}

和一个jquery函数

        function show_table(){
    $.post("http://localhost/crm/index.php/areaController/showarea",function(data){
    alert(data);
            });

            };

现在它的显示就像我在jquery中获取返回数据

                           [
    {"area_id":"1","area_name":"North","area_desc":"north",
    "area_created":"2016-04-11 14:02:05"}, 
      {"area_id":"2","area_name":"South","area_desc":"no", 
     "area_created":"2016-04-09 18:44:05"}
    ]

or like 


     Array (
    [0] => stdClass Object ( [area_id] => 1 [area_name] => North [area_desc]
        => Mirpur 1 [area_created] => 2016-04-11 14:02:05 )

   [1] => stdClass Object ( [area_id] => 2 [area_name] => North area_desc]=>
  area_desc [area_created] => 2016-04-09 18:44:15 )

  [2] => stdClass Object ( [area_id] => 3 [area_name] => west [area_desc] =>
 west [area_created] => 2016-04-10 19:34:27 ) 

 )

所以有人可以建议我如何通过jquery获得area_name,area_desc的值!

1 个答案:

答案 0 :(得分:0)

步骤1:使用以下功能替换您的功能show_list()

<?php   
public function show_list()
{

    $query = $this->db->get('area_list');
    $area_list = $query->result_array();

    return $area_list;
}
?>

步骤2:用此代码替换脚本函数show_table()

<script>
function show_table()
{

    $.post("http://localhost/crm/index.php/areaController/showarea",function(data){
        if(data != null)
        {
            $.each(data, function(i, val) {
                alert(val['area_id']);
                alert(val['area_name']);
                alert(val['area_desc']);
            });
        }   
     });
}
</script>

这将解决您的问题,试试这个并告诉我,如果您有任何错误......