我想在codeigniter中使用typeahead.js实现自动完成搜索

时间:2019-11-05 07:55:09

标签: jquery mysql ajax codeigniter typeahead.js

我是Codeigniter的新手。我想使用typeahead.js来实现自动搜索,但是当我单击搜索栏时却没有任何反应,而我正在使用XAMPP服务器和mysql数据库。有人可以帮我吗。 我正在使用typeahead.js,codeigniter来实现。请我不知道为什么它不起作用。请可以有人帮我。

<script>
$(document).ready(function(){
  var sample_data = new Bloodhound({
   datumTokenizer: Bloodhound.tokenizers.obj.whitespace('username'),
   queryTokenizer: Bloodhound.tokenizers.whitespace,
   prefetch:'<?php echo base_url(); ?>search/fetch',
   remote:{
    url:'<?php echo base_url(); ?>search/fetch/?query=%QUERY',
    wildcard:'%QUERY'
   }
  });
  

  $('#prefetch.typeahead').typeahead(null, {
   name: 'search_box',
   display: 'name',
   source:sample_data,
   limit:10,
   templates:{
    suggestion:Handlebars.compile('<div class="row"><div class="col-md-2" style="padding-right:5px; padding-left:5px;"><img src="student_image/{{image}}" class="img-thumbnail" width="48" /></div><div class="col-md-10" style="padding-right:5px; padding-left:5px;">{{name}}</div></div>')
   }
  });
});
</script>
<form class="navbar-form navbar-right hidden-sm">
              <div class="form-group">
                <div class="input-group" >
                <span class="input-group-addon">Search</span>
                <div id="prefetch">
                <input type="text" class="form-control typeahead" placeholder="Search people" id="search_box" name="search_box">
              </div>
              </div>
            </div>
          </form>

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Search extends CI_Controller {

function __construct() {
      parent::__construct();
      }
  
function index() {

$this->load->view('components/header');
$this->load->view('pages/newsfeed');
$this->load->view('components/footer');
  }
function fetch(){

$this->load->model('search_model');
echo $this->search_model->fetch_data($this->uri->segment(3));

  }
}  

?>

<?php 
class Search_model extends CI_Model {

function fetch_data($query){
$this->db->like('username', $query);
$query = $this->db->get('Client');
if($query->num_rows() > 0)
{
foreach($query->result_array() as $row) {
$output[] = array( 'username'  => $row["username"],
'image'  => $row["profile_image"]
);
}
echo json_encode($output);
}
}
}
?>

0 个答案:

没有答案