2017-03-02 46 views
0

現在球員我知道這是一個簡單的錯誤,但無論我嘗試我無法訪問json值,每當我使用警報後解析json它顯示我undefined 爲什麼是由什麼引起的? 這裏是我的代碼 腳本無法在codeigniter中訪問我的ajax成功json值

function getfriend_requests() 
{ 
var id=$('.id_data').attr('value'); 

jQuery.ajax({ 
       type:'POST', 
       url:'<?php echo base_url("user/getallfriends"); ?>', 
       data:{id:id}, 
       dataType:'json', 
       success:function(data) 
       { 

        var ParsedObject = JSON.stringify(data);    
        var json = $.parseJSON(ParsedObject); 
        alert(json); 
        $.each(json,function(key,data) 
        { 
         alert(data.object); 
        }); 
      } 
      }); 
} 

現在控制器

public function getallfriends() 
{ 
    $id=$this->input->post('id'); 
    $this->load->model('Pmodel'); 
    $data['senders']=$this->Pmodel->get_all_user_friends_sender($id); 


    $data['recievers']=$this->Pmodel->get_all_user_friends_reciever($id); 

    echo json_encode($data); 
} 

現在模型

public function get_all_user_friends_sender($id) 
{ 


    $this->db->select('*'); 
    $this->db->from('user_friend'); 
    $this->db->join('user_data', 'user_friend.senders_id = user_data.id'); 
    $this->db->join('user', 'user_friend.senders_id = user.id'); 
    $this->db->where('user_friend.senders_id',$id); 

    $query = $this->db->get(); 



     $row = $query->result_array(); 
    // print_r($row); 
     return($row); 



} 
public function get_all_user_friends_reciever($id) 
{ 

    $this->db->select('*'); 
    $this->db->from('user_friend'); 
    $this->db->join('user_data', 'user_friend.recievers_id = user_data.id'); 
    $this->db->join('user', 'user_friend.recievers_id = user.id'); 
    $this->db->where('user_friend.recievers_id',$id); 

    $query = $this->db->get(); 

     $row = $query->result_array(); 
    // print_r($row); 
     return($row); 



} 

現在,當我試圖返回與result_array IY值顯示我不確定值,但如果我使用$ row_array,它只會從每個模型中返回單個值。 你能告訴我我要去哪裏嗎? responseenter image description here

+0

爲什麼要將響應串聯起來以便在下一行再次將它解析回json?你已經爲你的ajax調用設置了'json'作爲dataType,所以它應該已經是一個json對象。你還應該發佈你從PHP返回的json響應。 –

+0

在你的ajax調用的響應部分中做一個'console.log(data)'來查看你的瀏覽器必須說的內容 –

+0

由於'$ query-> result_array()'你擁有'array的'json,所以在控制檯上看到'console.log(data);'上的輸出是什麼。 –

回答

0

在控制器試圖改變

echo json_encode($data);

$this->output->set_content_type('application/json'); 
$this->output->set_output(json_encode($data)); 
+0

仍然顯示undefined @Gerard –

+0

在json響應中,你沒有數組,所以你不能做$。每個json。你必須做$ .each從json.senders和$ .each從json.receivers並移除'var ParsedObject = JSON.stringify(data); var json = $ .parseJSON(ParsedObject);'你的回覆是json – Gerard

+0

我該如何做到這一點對於發件人和接收者都可以請指導我@Gerard –

1

array of objects在JSON響應因此在成功嘗試的功能像這樣..

   $.each(json,function(key,data) 
        { 
         alert(data.key);//where key is key of pointing object 
        }); 
+0

它仍然呈現出不確定的@Hekmat –

+0

是什麼樣的價值觀裏面對象在控制檯中。 –

+0

看到編輯答案@Hekmat –