研究了三天自动补全jquery.autocomplete.js。其中优化的程度很大。特别是和后台的交互。我采用的是前台静态缓存。
1.加载的js、css
2、autocomplete主体
3、后台 这里是根据我的项目来拼接json,准确的来说是拼接String ,因为我前台转换为json
1.加载的js、css
- <script type="text/javascript" src="/front/scripts/jquery/jquery-1.4.2.min.js"></script>
- <script type="text/javascript" src="/front/scripts/autocomplete/jquery.autocomplete.js"></script>
- <link rel="stylesheet" type="text/css" href="/css/jquery.autocomplete.css" />
- <input type="text" name="fund_code" id="fund_code" />
- <div id="getdata"></div>
2、autocomplete主体
- <%-- 自动补全代码--%>
- <script type="text/javascript">
- $(document).ready(function(){
- var data="";
- $.ajax({
- type: "post",
- url: "AnnouncementAction.action",
- dataType: "text",
- success: function(msg)
- {
- $("#getdata").data("getdata",msg);//1、存放数据
- },
- async:false
- });
- //alert($("#getdata").data("getdata"));
- });
- $(function(){
- var data = $("#getdata").data("getdata");//2、获取数据
- var datas = eval("(" + data + ")")//数据转换成json格式
- $("#fund_code").autocomplete(datas, {
- minChars: 1,
- matchCase:false,//不区分大小写
- autoFill: false,
- max: 10,
- width:196,
- formatItem: function(row, i, max,term) {
- var v = $("#fund_code").val();
- return row.name + " (" + row.code + ")";
- if(row.code.indexOf(v) == 0 || row.name.indexOf(v)==0)
- {
- return row.name + " (" + row.code + ")";
- }
- else
- return false;
- },
- formatMatch: function(row, i, max) {
- return row.name + " (" + row.code+")";
- },
- formatResult: function(row) {
- // alert(row.code);
- return row.code;
- },
- reasultSearch:function(row,v)//本场数据自定义查询语法 注意这是我自己新加的事件
- {
- //自定义在code或spell中匹配
- if(row.data.code.indexOf(v) == 0 || row.data.name.indexOf(v) == 0)
- {
- return row;
- }
- else
- return false;
- }
- });
- });</script>
3、后台 这里是根据我的项目来拼接json,准确的来说是拼接String ,因为我前台转换为json
- public void Autocomplete(){
- //getResponse().setCharacterEncoding("utf-8"); //必须
- FundBusService fs = new FundBusService();
- List<DataRow> list = fs.queryFundLike();
- System.out.println(list.get(0).getString("investadvisorabbrname"));
- String jsonStr="";
- for(int i=0;i<list.size();i++){
- jsonStr += "{name:"+'"'+list.get(i).getString("secuabbr")+'"'+",code:"+'"'+list.get(i).getString("secucode")+'"'+"},";
- }
- String jsonStr_new =jsonStr.substring(0,jsonStr.length()-1);
- String jsonStr_final="["+jsonStr_new+"]";
- try {
- getResponse().getWriter().print(jsonStr_final);
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return null;
- }
- 是我拼接的测试代码
- public static void main(String[] args) {
- String json = "{name:\"深圳\",code:\"00001\","+
- "spell:\"sgs\"},{name:\"广州\",code:\"00001\","+
- "spell:\"sghs\"}";
- String ss ="["+json+"]";
- System.out.println(ss);
- }
根据 http://hzywy.iteye.com/blog/1901325