前端代码
先引用 <script type="text/javascript" src="/js/plugin/jquery.autocomplete.min.js"></script>
<link rel="Stylesheet" href="/js/plugin/jquery.autocomplete.css" />
在界面加载完成后触发
$(document).ready(function () {
autoComple();
});
function autoComple(){
$("#s_customerId").autocomplete("/cnf/queryCnfCustomerBycId.action",
{
max: 12, //列表里的条目数
minChars: 3, //自动完成激活之前填入的最小字符
width: 300, //提示的宽度,溢出隐藏
scrollHeight: 300, //提示的高度,溢出显示滚动条
matchContains: true, //包含匹配,就是data参数里的数据,是否只要包含文本框里的数据就显示
autoFill: false, //自动填充
parse: function(data) { //这里是转换后台的数据,因为后台返回的时候是一个字符串,不转换会只显示一行
return $.map(eval(data), function(row) {
return {
data: row,
value: row.name,
result: row.name + " <" + row.code + ">"
}
});
},
formatItem: function(data, i, max) {
return data.code + '【' + data.name + '】';
},
formatMatch: function(data, i, max) {
return data.code + data.name;
},
formatResult: function(data) {
return data.code;
}
}).result(function(event, data, formatted) {
$("#s_customerId").val(data.code);
});
}
result方法是jQuery Autocomplete插件里的重要方法,它在用户在选定了某个条目时触发。data参数为选中的数据。
formatItem、formatMatch、formatResult是自定提示信息的关键。
formatItem作用在于可以格式化列表中的条目,比如我们加了“I”,让列表里的字显示出了斜体。
formatMatch是配合formatItem使用,作用在于,由于使用了formatItem,所以条目中的内容有所改变,而我们要匹配的是原始的数据,所以用formatMatch做一个调整,使之匹配原始数据,
formatResult是定义最终返回的数据,比如我们还是要返回原始数据,而不是formatItem过的数据。
台代码,具体实现代码可以忽略,就是查询数据后组装成json数组,返回。
public void queryCustomerIdAndName(){
CnfCustomerInfo cust = new CnfCustomerInfo();
cust.setCustomerId(q); //默认的参数变量,奇葩
try{
List<Object> list = this.cnfService.queryForList("cnf.queryCustomerBycId",cust,10);
CnfCustomerInfo info = null;
JSONObject json = null;
JSONArray array = new JSONArray(); //添加到jsonArray数组
for(Object obj : list){
json = new JSONObject();
info = (CnfCustomerInfo) obj;
json.put("code", info.getCustomerId());
json.put("name", info.getCustomerNameCh());
array.add(json);
}
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write(array.toString());
}catch (Exception e) {
e.printStackTrace();
}
}
本文详细介绍了如何使用jQuery Autocomplete插件实现前端自动补全功能,包括初始化配置、自定义提示信息及后台数据处理流程。通过实例代码展示了如何从后台获取数据并组装成JSON数组进行返回。
577

被折叠的 条评论
为什么被折叠?



