我尝试使用从站点获得的代码在codeignter中执行自动完成功能,但是它对我不起作用.有人可以找到问题吗?
我使用的视图功能如下
<html>
<head>
<title>Autocomplete</title>
<script src="<?php echo base_url().'js/jquery.autocomplete.js'?>"></script>
<script src="<?php echo base_url().'js/jquery-1.6.4.js'?>"></script>
<script type="text/javascript">
$(function() {
$( "#username" ).autocomplete({ //the recipient text field with id #username
source: function( request, response ) {
$.ajax({
url: "http://localhost/autocomplete/index.php/autocontroller/search_username",
dataType: "json",
data: request,
success: function(data){
if(data.response == 'true') {
response(data.message);
}
}
});
}
});
});
</script>
</head>
<body>
<h1>Autocomplete</h1>
<input type="text" id="username" value="" />
</body>
</html>
我使用的控制器如下
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of autocontroller
*
* @author Sivam
*/
class autocontroller extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->database();
}
function index()
{
$this->load->view('autoview');
}
function search_username()
{
$username = trim($this->input->get('term', TRUE)); //get term parameter sent via text field. Not sure how secure get() is
$this->db->select('fname');
$this->db->from('users');
$this->db->like('fname', $username);
$this->db->limit('5');
$query = $this->db->get();
if ($query->num_rows() > 0)
{
$data['response'] = 'true'; //If username exists set true
$data['message'] = array();
foreach ($query->result() as $row)
{
$data['message'][] = array(
'label' => $row->fname,
'value' => $row->fname
);
}
}
else
{
$data['response'] = 'false'; //Set false if user not valid
}
echo json_encode($data);
}
}
?>
解决方法:
我不明白你为什么使用
$data['message'][] = array(
'label' => $row->fname,
'value' => $row->fname
);
您可以尝试按一维数组.
$data['message'] = array(
'label' => $row->fname,
'value' => $row->fname
);
我也通过关注此.http://www.jamipietila.fi/codeigniter-and-autocomplete-with-jquery/来使用自动完成功能.请尝试一下…它对我有用..希望它也对您有用.