【发布时间】:2017-06-10 08:56:10
【问题描述】:
我正在尝试在其中 AJAX 自动完成的 codeigniter 文件中进行实时搜索
$(this).ready( function()
{
$("#id").autocomplete
({
minLength: 1,
source:
function(req, add){
$.ajax({
url:'<?php echo site_url('autocomplete/lookup'); ?>',
dataType: 'json',
type: 'POST',
data: req,
success:
function(data){
if(data.response =="true"){
add(data.message); // displays the retrieved data
}
},
});
},
});
});
自动完成控制器的查找功能是
public function lookup(){
// process posted form data
//echo $this->input->post('term'); exit;
$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
}
}
if('IS_AJAX')
{
echo json_encode($data); //echo json string if ajax request
}
else
{
$this->load->view('data_view',$data); //Load html view of search results
}
}
我可以使用视图代码中的 add(data.message) 访问以 json 编码形式返回的数据。 我无法在 ajax 代码之外访问这些数据,我应该怎么做才能让我在我的 php 代码中使用这个返回的数据。
【问题讨论】:
-
把
console.log(data)放到你的成功函数中。不要提醒它 -
@NishantNair 我没有使用警报,我使用了 add 将检索到的数据添加到下拉列表中
-
抱歉,我看错了。 add 方法在做什么?实施在哪里?
-
@NishantNair 它是 jquery 的一部分,可能是因为 add 函数是我读到的代码的一部分,唯一提供的解释是它显示了数据
-
您是否尝试过使用以下答案。您应该在使用前对数据进行解码
标签: php jquery json ajax codeigniter