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