jQuery-UI官方地址:Autocomplete | jQuery UI
前端页面代码:
<html lang="us">
<head>
<meta charset="utf-8">
<title>jQuery-UI Example</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.1/themes/base/jquery-ui.css">
<style>
body{
font: 62.5% "Trebuchet MS", sans-serif;
margin: 50px;
}
select {
width: 200px;
}
</style>
</head>
<body style="text-align:center">
<h1>jQuery-UI Autocomplete Ajax</h1>
<br/><br/>
<div>
<input id="autoByAjax" title="type">
<button id="btn" type="button">submit</button>
</div>
</body>
</html>
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.1/jquery-ui.js"></script>
<script>
$(function(){
var dataArray=[];
var option = {
max: 12, //列表里的条目数
minChars: 0, //自动完成激活之前填入的最小字符
width: 400, //提示的宽度,溢出隐藏
scrollHeight: 300, //提示的高度,溢出显示滚动条
matchContains: false, //包含匹配,就是data参数里的数据,是否只要包含文本框里的数据就显示
autoFill: true, //自动填充
minLength: 0,
select: function (event, ui) {
$("#autoByAjax").val(ui.item.label); // display the selected text
}
};
$.ajax({
url: "./aa.php",
type: "GET",
dataType: "json",
success: function(data){
console.log(data)
if(data.success){
var reslist = data.result;
for(var i=0; i<reslist.length; i++){
var vo = reslist[i];
dataArray.push({id :vo, label: vo});
}
}
}
});
//$("#autoByAjax").autocomplete({source: dataArray}, option);
$("#autoByAjax").autocomplete({source: dataArray}, option).on('focus', function() { $(this).keydown(); });
$("#btn").click(function(){
var v = $("#autoByAjaxVal").val();
alert(v);
});
});
</script>
后端接口代码:
<?php
$result = ["北京", "上海", "四川", "河南", "河北", "安徽"];
exit(json_encode(['success'=>1, 'result'=>$result]));