|
|
BootstrapPlugin - typeahead-ex 使用笔记
1) bootstrap官方的typeahead插件不支持ajax方式展示数据。这个插件作为扩展,让typeahead有了ajax的功能。
留档备份。
2) 官方文档 & 官方DEMO
https://github.com/tcrosen/twitter-bootstrap-typeahead
3) 代码
<!DOCTYPE HTML><html lang="zh"> <head> <title>Bootstrap Base</title> <base href="<%=basePath %>" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link type="text/css" rel="stylesheet" href="css/bootstrap.min.css" /> <script type="text/javascript" src="js/jquery-1.8.3.min.js"></script> <script type="text/javascript" src="js/bootstrap.min.js"></script> <script type="text/javascript" src="js/bootstrap-typeahead-ex.js"></script> <script type="text/javascript" src="js/mockjax.js"></script> <script type="text/javascript"> $(document).ready(function() { $("[rel='tooltip']").tooltip({placement: "right"}); $('#input1').typeahead({ source: [ { id: 1, name: 'Toronto' }, { id: 2, name: 'Montreal' }, { id: 3, name: 'New York' }, { id: 4, name: 'Buffalo' }, { id: 5, name: 'Boston' }, { id: 6, name: 'Columbus' }, { id: 7, name: 'Dallas' }, { id: 8, name: 'Vancouver' }, { id: 9, name: 'Seattle' }, { id: 10, name: 'Los Angeles' } ], display: 'name', val: 'id', itemSelected: function(item, value, text) { alert(value); alert(text); } }); // ---------------------------------------------------------------------- $('#input2').typeahead({ ajax: { url: "ajax/test", method: "GET", triggerLength: 1, preProcess: function(data) { // 这个方法非常重要!// 本插件要求处理一个javascript对象而不是一个json字符串// 同时应当注意 $.parseJSON方法要求的json字符串必须用双引号引用属性名! return $.parseJSON(data); } }, itemSelected: function(item, value, text) { alert(value); alert(text); } }); }); </script> </head> <body><label>输入框1 <input type="text" id="input1" /></label> <br/><label>输入框2 <input type="text" id="input2" /></label> </body></html>
import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.ResponseBody;@Controller@RequestMapping("/ajax")public class AjaxController {@ResponseBody@RequestMapping(value = "/test", method = { RequestMethod.GET })public String test(@RequestParam("query") String query){return "[{ \"id\": 1, \"name\": \"New York\" }, { \"id\": 2, \"name\": \"Shanghai\"}]";}}
 |
|