controller:welcome.php
public function lookup()
{
$keyword = trim($_GET['term']);
$data['response'] = 'false';
$query = $this->Main_tutorial->lookup($keyword);
print_r($query);
if( ! empty($query) )
{
$data['response'] = 'true';
$data['message'] = array();
$data['auto_com'] = array();
foreach( $query as $row )
{
$data['message'][] = array('tutorial_name' => $row['tutorial_name']);
$data['auto_com'][] = $row['tutorial_name'];
}
}
if('IS_AJAX')
{
echo json_encode($data['auto_com']);
}
else
{
$this->load->view('index',$data);
}
}
view:index.php
<html>
<head>
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>resource/css/jquery-ui.css">
<link rel="stylesheet" href="http://static.jquery.com/ui/css/demo-docs-theme/ui.theme.css" type="text/css" media="all" />
</head>
<body>
<input type="text" class="search-bg__text" name="tutorial_name" id="tutorial_name">
<script src="<?php echo base_url(); ?>resource/js/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#tutorial_name").autocomplete({
source:"<?php echo base_url(); ?>welcome/lookup",
minLength:1,
select:function(b,c)
{
var a=c.item.value;
a=encodeURIComponent(a);
location.href=a+"-tutorial";
return false
}
});
});
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js" type="text/javascript"></script>
</body>
</html>
model:Main_tutorial.php
public function lookup($keyword)
{
$this->db->select('tutorial_name')->from('tutorial');
$this->db->like('tutorial_name',$keyword,'after');
$query = $this->db->get();
$result = $query->result_array();
return $result;
}
在此代码中,我想使用codeigniter创建一个自动完成建议框。现在当我在tutorial_name输入字段中写入内容并检查元素然后选择网络然后点击链接它会向我显示输出但发现但我无法知道原因时会发生什么?那么我该如何解决这个问题?请帮助我。
谢谢
答案 0 :(得分:0)
在autocomplete()
中,您需要输出为 json 格式。在这里,您使用echo json_encode($data['auto_com']);
打印json数据但在此之前您还显示数据print_r($query);
。这会创建无效的json输出。所以你必须删除它。另请注意,您的if('IS_AJAX')
将始终为true
public function lookup()
{
$keyword = trim($_GET['term']);
$data['response'] = 'false';
$query = $this->Main_tutorial->lookup($keyword);
if( ! empty($query) )
{
$data['response'] = 'true';
$data['message'] = array();
$data['auto_com'] = array();
foreach( $query as $row )
{
$data['message'][] = array('tutorial_name' => $row['tutorial_name']);
$data['auto_com'][] = $row['tutorial_name'];
}
}
if('IS_AJAX') //This condition always become true
{
echo json_encode($data['auto_com']);
}
else
{
$this->load->view('index',$data);
}
}