2016-04-11 75 views
0

我有在模型中codeignitor函數如何訪問stdClass的對象在arrray jQuery中

 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的值!

+0

'data [index] .area_name'?例如'data [0] .area_name' –

+0

顯示undefined @ Sandeep Nayak –

+0

在使用'data'之前,您需要使用'$ .parseJSON(data);'; – itzmukeshy7

回答

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> 

這將解決您的問題,試試這個,讓我知道,如果你有任何錯誤...