最近在做项目中,遇到了这样一个业务需求,文本框中输入一个汉字或者字母就能通过ajax向后台数据库发送请求,然后把匹配的数据获取到下拉列表中可进行选择;
效果如下:
;
网上关于这个有很多说法和版本,但是我自认为解释都不够详细,下面我来介绍一下:(本次开发:spring+mvc)
step1:下载组件,进入jQuery组件库,然后搜索 bootstrap_typeahead直接下载;
step2:把其中的bootstrap.css和bootstrap-typeahead.js以及jquery-1.8.3.min.js导入项目对应的目录下;
step3:如果想先模拟数据的话,你可以在jsp页面上先模拟数据来判断组件是否合适:
1》数据源模拟:
<!DOCTYPE html>
<html>
<head>
<link href="css/bootstrap.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div style="margin: 50px 50px">
<label for="product_search">Product Search: </label>
<input id="product_search" type="text" data-provide="typeahead">
</div>
<script src="js/jquery-1.8.3.min.js"></script>
<script src="js/bootstrap-typeahead.js"></script>
<script>
$('#product_search').typeahead({
source: [
{ id: 1, full_name: 'Toronto', first_two_letters: 'To' },
{ id: 2, full_name: 'Montreal', first_two_letters: 'Mo' },
{ id: 3, full_name: 'New York', first_two_letters: 'Ne' },
{ id: 4, full_name: 'Buffalo', first_two_letters: 'Bu' },
{ id: 5, full_name: 'Boston', first_two_letters: 'Bo' },
{ id: 6, full_name: 'Columbus', first_two_letters: 'Co' },
{ id: 7, full_name: 'Dallas', first_two_letters: 'Da' },
{ id: 8, full_name: 'Vancouver', first_two_letters: 'Va' },
{ id: 9, full_name: 'Seattle', first_two_letters: 'Se' },
{ id: 10, full_name: 'Los Angeles', first_two_letters: 'Lo' }
],
display: 'full_name'
});
</script>
</body>
</html>
2》直接发送ajax请求从数据源获取数据:
<script>
$("#DItr1td2Select").typeahead({
ajax: {
url: "${ctx}/referral/getPrimaryDiagnosis",
timeout: 500,
displayField: "result",
triggerLength: 1,
dataType: 'JSON',
method: "get",
loadingClass: "loading-circle",
preDispatch: function (query) {
return {
query: query, //查询条件
limit: