自己做的jquery的autocomplete的一个例子

转载自:http://dada-fangfang.iteye.com/blog/695464


首先下载jquery.js和jquery.autocomplete.js 

注意:jquery.js 要放在jquery.autocomplete.js前面。 
还有个样式jquery.autocomplete.css , 随意下载。 

首先js代码如下 
$().ready(function() { 
$("#searchText").autocomplete("$!  {request.contextPath}/hrHiPersons!ajaxSelectPerson.action", { 
minChars: 0, 
max: 12, 
autoFill: true, 
mustMatch: true, 
matchContains: false, 
scrollHeight: 220, 
            formatItem: function(item) { 
                return item[0]; 
            } 
}); 
}); 
struts2的url应该不陌生吧 
autocomplete的参数,这里不写了,可以参考 
http://chenling1018.blog.163.com/blog/static/148025420101250354380/ 
他写的很详细,我也测过,基本都描述的差不多. 

以前js方法的item参数,就是后台返回的json流,一下是java代码 
public String ajaxSelectPerson(){ 
try { 
String search = getRequest().getParameter("q"); 
if(search==null||search.length()==0) return null; 
List<String> names = new ArrayList<String>(); 
                   names.add("张三"); 
                   names.add("李四"); 
                   names.add("王五"); 
                  getResponse().setCharacterEncoding("UTF-8"); 
JSONArray json = JSONArray.fromObject(names); 
PrintWriter out = getResponse().getWriter(); 
out.print(json); 
        out.flush(); 
        out.close(); 
        return null; 
} catch (Exception e) { 
e.printStackTrace(); 

return null; 

他默认是get提交,而且默认接受的参数是q,一般不用修改。 
其次主要是乱码的问题,ajax的传输都是utf-8,所以我们尽量都转成utf-8(tomcat,jsp),然后把response也设置成utf-8,这样中文就没问题了。 
还有个忘了说, 需要修改autocomplete的源码,主要是为了中文的输入识别问题 
在199-200行 
$(input.form).unbind(".autocomplete"); 

修改为: 
$(input.form).unbind(".autocomplete").bind("input", function() {   
     onChange(0, true);   
}); 

OK了,效果还是不错的,比原先手写的jquery代码好多了,简单实用。


posted @ 2014-03-23 22:29  奋斗中的毛毛虫  Views(148)  Comments(0Edit  收藏  举报