javascript - 如何在 CodeIgniter 中创建自动完成搜索字段?

标签 javascript php jquery ajax codeigniter

我正在 CodeIgniter 中创建自动完成搜索字段,但它无法正常工作。有 10 个的限制,但每次当我输入字符时,列表变得越来越长,就像图像中显示的那样:

enter image description here

images of autocomplete search field

这是我的 Controller :

    function search_fields(){

    $country_id = $this->input->get('term');
    $data['var']= $this->Travel->search_field($country_id); 
    echo json_encode($data['var']);

}

这是我的模型:

 function search_field($country_id){
    $this->db->distinct();
    $this->db->select("destination");
    $this->db->from('travels_detail');
    $this->db->like('destination', $country_id);
     $this->db->group_by('travels_detail.destination');
     $this->db->limit(10);
    $query = $this->db->get();
    return $query->result();
}

这是我的观点:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $('#text').keyup( function() {
        var min_length = 0; 
    var keyword = $('#text').val();
    if (keyword.length >= min_length) {
        $.ajax({
            url: 'http://localhost/new/index.php/travels/search_fields',
            type: 'POST',
             dataType: 'json',
            data: { term: $("#text").val()},
            success:function(data){
                $.each(data, function() {
  $.each(this, function(k, v) {
      $("#demo").append("<li>" + v + "</li>");
  });
});
     }
        });
    } else {
        $('#demo').hide();
    }
});
});

</script>
</head>

<body>
<form method="post">
 <input type="text" name="text" id="text" autocomplete="off" > 
</form>
<ul id="demo"> </ul>
</body>
</html>

我还希望用户可以从下拉列表中选择输入字段的值。有人知道吗?

最佳答案

您忘记从 #demo 中清除 html。当 Ajax 中出现成功属性时,从 #demo 中删除所有内容:

success:function(data){
   $("#demo").html('');
    $.each(data, function() {
      $.each(this, function(k, v) {
          $("#demo").append("<li>" + v + "</li>");
      });
    });
}

关于javascript - 如何在 CodeIgniter 中创建自动完成搜索字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40887251/

相关文章:

php - 更好的 SQL 字符串清理功能

php - MySQL - 将值插入表中的 PHP 表单?

javascript - 工具提示器工作了。现在 : TypeError: $ ('.tooltip' ). tooltipster 不是一个函数

javascript - `this` 的属性在 setTimeout 内未定义

javascript - Masonry broken(可能是经典)

javascript - d3 力有向图向下力模拟

javascript - 未捕获的类型错误 : Cannot read property 'style' of null concerning a script in an echo

javascript - 为可拖动对象设置位置、顶部和左侧

javascript - 为 url 上的某些 div 传递 jquery 向上滑动命令?

javascript - 通过变量访问json对象值