【问题标题】:Using AJAX returned JSON encoded data in Codeigniter在 Codeigniter 中使用 AJAX 返回 JSON 编码数据
【发布时间】:2017-01-27 06:30:28
【问题描述】:

我对 codeigniter 比较陌生。当我尝试使用 AJAX 在我的数据库上执行搜索操作时,代码成功返回并检索了数据,但是,此数据是 JSON 编码的,并且在我的视图的 javascript 部分中,因此我无法使用codeigniter的json_decode函数

public function lookup(){
    $keyword = $this->input->post('term');
    $data['response'] = 'false'; //Set default response
    $query = $this->MAutocomplete->lookup($keyword); //Search DB
    if( ! empty($query) )
    {
        $data['response'] = 'true'; //Set response
        $data['message'] = array(); //Create array
        foreach( $query as $row )
        {
            $data['message'][] = array( 
                                    'id'=>$row->id,
                                    'value' => $row->firstname,

                                 );  //Add a row to array
        }
    }          
        echo json_encode($data); //echo json string
}

数据在 javascript 中作为 data.message 访问。 请告诉我无论如何我可以在我的程序的 php 部分中使用这些数据

<?php
class MAutocomplete extends CI_Model{
function lookup($keyword){
    $this->load->database();
    $this->db->select('*');
    $this->db->from('Students');
    $this->db->like('firstName',$keyword,'after');
    $query = $this->db->get();    
     // echo '<pre>'; print_r($query->result()); exit;
    return $query->result();
}
}

【问题讨论】:

  • 你能发布你的模型的功能吗?你以哪种格式获得结果表单数据库?
  • @HikmatSijapati 我已按要求添加了型号代码
  • 查看答案希望你解决了。
  • 你说“请告诉我无论如何我可以在我的程序的 php 部分使用这些数据”是什么意思?请进一步解释您的问题。

标签: json ajax codeigniter


【解决方案1】:

我认为您需要使用JSON.parse()解析Ajax成功函数中的json响应。像这样..

$.ajax({
url:'',//your url
dataType:'JSON',
data:'',//your data 
success:function(response){
data = JSON.parse(response);
alert(data.message.value);//alerts value
}
});

在控制器中使用count 而不是空的。检查数组

 if( count($query) >0 )
    {
        $data['response'] = 'true'; //Set response
        $data['message'] = array(); //Create array
        foreach( $query as $row )
        {
            $data['message'][] = array( 
                                    'id'=>$row->id,
                                    'value' => $row->firstname,

                                 );  //Add a row to array
        }
    }       

【讨论】:

    【解决方案2】:

    你应该使用来回应:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-10
      • 1970-01-01
      • 2016-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多