无法在codeigniter中访问我的ajax成功中的json值

时间:2017-03-02 16:30:12

标签: php jquery json ajax codeigniter

现在我知道这是一个简单的错误,但无论我尝试什么,我无法访问json值,每当我使用警报后解析json它显示我undefined 它为什么会引起? 这是我的代码 脚本

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返回值时,我显示未定义的值但是如果我使用$ row_array它只返回每个模型的单个值。 你能告诉我哪里出错了吗? response enter image description here

2 个答案:

答案 0 :(得分:1)

你在json响应中有array of objects所以在成功函数中尝试这样..

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

答案 1 :(得分:0)

在您的控制器中尝试更改

function createLink2(record) { // Link types var output = { 'ntid': 'https://example.com/profile/', 'email': 'mailTo:' }; // Vars var keys = Object.keys(output); // Loop over our object keys record = keys.reduce(function(obj, currKey) { if (obj[currKey] != undefined) { obj[currKey] = '<a href="' + output[currKey] + obj[currKey] + '" target="_blank">' + obj[currKey] + '</a>' } return obj; }, record); return record; } console.log(createLink2({ntid: "12345", email: "joebob@gmail.com"}));

echo json_encode($data);