codeigniter在键入部分值时选择box load

lokaqttq  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(284)

如何使用ajax在codeigniter like live search中创建selectbox。在selectbox上键入时,自动提示相关数据。比如谷歌搜索。我已经在表上的实时搜索代码。但我的要求是制作选择框。因为我有大量的数据要加载selectbox。

fv2wmkja

fv2wmkja1#

bappoint.php(控制器)

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

class Bappoint extends CI_Controller {
function index()
{
     $this->load->view('home');
}
function search()
{
  header('Content-Type: application/json');
  $this->load->model('common_model');
  $key = $this->input->post('search_key');
  $users = $this->common_model->get_search($key);
  //$this->output->enable_profiler();
  echo json_encode($users->result());
}
}
?>

common_model.php(模型)

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

class Common_model extends CI_Model
{
    public function get_search($key)
    {
        $this->db->like('fname', $key, 'both');
        return $this->db->get('users');
    }
}?>

home.php(视图)

<html>
<head>
<style>
    #users
    {
      position: absolute;
      max-height: 250px;
      border: 1px solid #888686;
      width: 100%;
      z-index: 1000;
      background-color: #fff;
      overflow-y: auto;
    }
    #users ul
    {
      padding-left: 0px;
      margin-bottom: 0px;
    }
    #users  ul li
    {
      list-style: none;
      line-height: 30px;
      padding-left: 25px;

    }
    #users ul li:hover
    {
      background-color: #8e24aa;
      color:#fff;
      cursor: pointer;
    }
    #sblock
    {
      width: 300px;
    }
    </style>
</head>
<body>
    <div id="sblock">
          <input type="text" id="search_key">
          <div id="users"></div>
        </div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
  crossorigin="anonymous "></script>
<script type="text/javascript">
 $(document).ready(function(){

      $('#search_key').on('keyup', function(){
        $('#users').html('');
        var key = $('#search_key').val();
        if(key  != '')
        {
          $.ajax({
            url:'bappoint/search', //controllers url
            type:'post',
            data:{'search_key':key},
            success:function(json)
            {
              if(json.length >  0)
              {
                search_data =  '<ul>';
                $.each(json, function(key, val){
                  search_data += `<li>${val.fname}</li>`;
                });
                search_data += `</ul>`;
                $('#users').html(search_data);
              }
            }
          });
        }

      });
    });
</script>
</body>
</html>

mysql查询

CREATE TABLE `users` ( `id` INT NOT NULL AUTO_INCREMENT , `fname` VARCHAR(60) NOT NULL , PRIMARY KEY (`id`)) ENGINE = InnoDB;

相关问题