因為項目需要,需要做輸入框自動提示功能,之前我只是使用過這種功能,相信大家也都使用過,百度~現在要讓我自己做,好吧,還是百度一下,百度搜索“輸入框自動提示”,彈出一對頁面,也看了一堆文章,有自己開發的,也有插件的。
最后經過幾次試驗,我選擇了JQuery.Autocomplete這款插件,還行吧用著,支持本地也支持ajax訪問服務器,這款插件是基于jquery的,各位若有項目需要使用的,可以嘗試一把。源碼下載:JQuery.AutoComplete
本地自動提示的方式我就不說了,各位下載源碼之后看一下也就明白了,當然不明白的也可以問我,說一下ajax訪問服務器的方式吧,直接上代碼最為直接:
$(function(){
var onAutocompleteSelect =function(customer) {
$('#customerIdString').val(customer.data);
};
var options = {
serviceUrl: '${pageContext.request.contextPath}/TCustomer/getAllCustomer.koala',//獲取數據的后臺頁面
onSelect: onAutocompleteSelect,//選中之后的回調函數
extraParams: {selectedCustomerName:$.trim($("#selectedCustomerName").val())},//動態參數值
paramName: "selectedCustomerName",
noCache: false, //是否啟用緩存 默認是開啟緩存的
max:10,
autoFill:false
};
$('#selectedCustomerName').autocomplete(options);
});
這樣我們就可以把填入輸入框的值作為extraParams動態參數傳遞到后臺去,后臺直接request.getParameter("selectedCustomerName");就可以了。
值得注意的是,后臺應該返回什么樣的數據格式,這個插件需要注意的地方就是這塊了,如果不是他要求的格式的話,頁面會報js錯誤的,要求的數據格式必須是這樣的json串:
{"query":"A","suggestions":[{"data":"114e69b4-87a9-4c2b-aed4-1727568a92a7","value":"AAA111"},{"data":"531b59ca-8618-48f4-a6e8-963320e10159","value":"小人物_Amor"}]}
query后面的A是我輸入框傳入的參數,根據A模糊查詢出兩組數據,并以json的格式放在key為suggestions里。
后臺代碼:
@ResponseBody
@RequestMapping("/getAllCustomer")
public Object getAllCustomer(HttpServletRequest request,HttpServletResponse response)throws IOException{
List<Object> queryCustomerList = new ArrayList<Object>();
List<TCustomerDTO> allCustomer = new ArrayList<TCustomerDTO>();
//獲取前臺帶過來的動態參數
String selectedCustomerName = request.getParameter("selectedCustomerName");
//得到包含selectedCustomerName參數的對象
allCustomer = tCustomerApplication.findAllTCustomer();
for (Iterator iterator = allCustomer.iterator(); iterator.hasNext();) {
TCustomerDTO tCustomerDTO = (TCustomerDTO) iterator.next();
if(tCustomerDTO.getName().contains(selectedCustomerName)){
Map<String, Object> result = new HashMap<String, Object>();
result.put("value", tCustomerDTO.getName());
result.put("data", tCustomerDTO.getId());
queryCustomerList.add(result);
}
}
//構造規定的json數據格式
Map<String, Object> query_result = new HashMap<String, Object>();
Object json = JSONArray.toJSON(queryCustomerList);
query_result.put("query", selectedCustomerName);
query_result.put("suggestions", json);
Object json_map = JSONArray.toJSON(query_result);
System.out.println(json_map);
return json_map;
}
OK了,其實很簡單,當然你需要引入jquery,以及他所要求的其他兩個js文件,各位下載源碼后看示例就知道啦~