controller:Test.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Test extends CI_Controller
{
function __construct()
{
parent :: __construct();
$this->load->helper(array('form', 'url'));
$this->load->model('Fetch_data');
}
public function index()
{
$searchTerm = $_GET['term'];
$data['search'] = $this->Fetch_data->autocomplete($searchTerm);
$this->load->view('index',$data);
}
}
view:index.php
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<input type="text" name="colleges" id="colleges" class="form-control" />
<script>
$(function() {
$( "#colleges" ).autocomplete({
source: '<?php echo base_url("index.php"); ?>/test/index';
});
});
</script>
model:Fetch_data.php
<?php
class Fetch_data extends CI_Model
{
function __construct()
{
parent::__construct();
}
public function autocomplete($searchTerm)
{
$this->db->select('college_name,field');
$this->db->from('all_colleges');
$where = "short_name like '%".$searchTerm."%' or college_name like '%".$searchTerm."%'";
$this->db->where($where);
$this->db->order_by('college_name');
$query = $this->db->get();
$result = $query->result_array();
return $result;
}
}
我是ci的新人。使用此代码我想在codeigniter中创建一个自动完成建议框但是这段代码对我不起作用。那么,如何在ci中创建自动完成建议框,请告诉我我的代码中有什么问题可以使用此代码进行自动完成。
谢谢
答案 0 :(得分:0)
更新您可以尝试:
你的模特 Fetch_data.php
<?php
class Fetch_data extends CI_Model
{
function __construct()
{
parent::__construct();
}
public function autocomplete()
{
$this->db->select('college_name,field');
$this->db->from('all_colleges');
$this->db->order_by('college_name');
$query = $this->db->get();
$result = $query->result_array();
return $result;
}
}
控制器: Test.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Test extends CI_Controller
{
function __construct()
{
parent :: __construct();
$this->load->helper(array('form', 'url'));
$this->load->model('Fetch_data');
}
public function index()
{
$all_data = array();
$result = $this->Fetch_data->autocomplete(); //collect all college name
foreach($result as $key=>$value){
array_push($all_data, $value["college_name"]);
}
$data['search'] = $all_data;
$this->load->view('index',$data);
}
}
查看: index.php
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<input type="text" name="colleges" id="colleges" class="form-control" />
<input type='hidden' id='mydata' value='<?php echo json_encode($search);?>' />
<script>
$( function() {
var oData = $("#mydata").val();
oData = JSON.parse(oData);
$( "#colleges" ).autocomplete({
source: oData;
});
});
</script>
您可以获取所有的college_names并使用变量存储它,然后当您输入一个字母时,您不能再使用ajax,因为它已经存储了变量。
希望它能奏效。