(Codeigniter-jquery ui)自动填充无法正常工作

时间:2017-01-25 14:45:29

标签: php codeigniter jquery-ui

我的意图是搜索用户。但是自动完成功能对我不起作用。我想对此有所帮助。

以下是我的代码,

HTML

<input id="user-input" type="text" name="users" placeholder="Search User" autocomplete="on">

模型

function get_user($user) {

    $this->db->select('name');
    $this->db->like('name', $user);
    $query = $this->db->get('users');

    // echo $query; die;

    if($query->num_rows() > 0){
        foreach($query->result_array() as $row) {
            $row_set[] = htmlentities(stripslashes($row['name']));
        }

        echo json_encode($row_set); 
    }

}

控制器

public function user_search() {

    $this->load->model('users_model');

    if (isset($_GET['term'])){
        $user = strtolower($_GET['term']);
        $this->users_model->get_user($user);
    }

}

的js

$(function(){
  $("#user-input").autocomplete({
    source: "site/user_search",
    minLength: 1
  });
});

我正在使用jquery ui版本1.12

2 个答案:

答案 0 :(得分:2)

实际上这对我来说很好,为了简​​单起见我删除了模型。

在你看来

    <script src="jquery-3.1.1.min.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
     <script>
     $(function(){
      $("#user-input").autocomplete({
        source: "<?php echo base_url('site/user_search'); ?>",
        minLength: 1
      });
    });
    </script> 
 <input id="user-input" type="text" name="users" placeholder="Search User" autocomplete="on">

在您的站点控制器中

    function user_search()
    {

        $user = $_GET['term'];

        $query = $this
                      ->db
                      ->select('name')
                      ->like('name',$user)
                      ->get('users');

         if($query->num_rows() > 0){
            foreach($query->result_array() as $row) {
                $row_set[] = htmlentities(stripslashes($row['name']));
            }

            echo json_encode($row_set); 
        }
   }

答案 1 :(得分:0)

 Set label and value in json response key
 function user_search()
    {

        $user = $_GET['term'];

        $query = $this
                      ->db
                      ->select('name')
                      ->like('name',$user)
                      ->get('users');

         if($query->num_rows() > 0){
            foreach($query->result_array() as $row) {
                $new_row['label']=htmlentities(stripslashes($row['name']));
                $new_row['value']=htmlentities(stripslashes($row['name']));
                $row_set[] = $new_row; //build an array
            }

            echo json_encode($row_set); 
 }