在Codeigniter中使用AJAX返回JSON编码的数据
我对codeigniter比较陌生。当我试图使用AJAX在数据库上执行搜索操作时,代码返回成功并检索数据,但是,该数据是JSON编码的,并且在我视图的javascript部分,因此我无法使用codeigniter的JSON_解码功能在Codeigniter中使用AJAX返回JSON编码的数据,json,ajax,codeigniter,Json,Ajax,Codeigniter,我对codeigniter比较陌生。当我试图使用AJAX在数据库上执行搜索操作时,代码返回成功并检索数据,但是,该数据是JSON编码的,并且在我视图的javascript部分,因此我无法使用codeigniter的JSON_解码功能 public function lookup(){ $keyword = $this->input->post('term'); $data['response'] = 'false'; //Set default response
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();
}
}
我认为您需要使用json.parse()
,在Ajax的成功函数中解析json响应
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
}
}
在控制器中使用计数而不是空。要检查数组
return $this->output
->set_content_type('application/json')
->set_output(json_encode($data));
您应该使用以下命令来响应:
你能发布你的模型的函数吗?你从数据库中得到的结果是什么格式?@HikmatSijapati我已经按照要求添加了模型代码请看答案希望你能解决它。你说“请告诉我,我可以在我的程序的php部分使用这些数据”是什么意思?请进一步解释你的问题。
return $this->output
->set_content_type('application/json')
->set_output(json_encode($data));