2017-03-02 112 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 –