[easyUI] autocomplete 简单自动完成以及ajax从服务器端完成
Posted zZ
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[easyUI] autocomplete 简单自动完成以及ajax从服务器端完成相关的知识,希望对你有一定的参考价值。
通过id取input标签对象,调用autocomplete方法
<script> var sources = [ "ActionScript", "AppleScript", "Asp", "COBOL", "ColdFusion", "Erlang", "Fortran", "Groovy", "Haskell", "Java", "javascript", "Lisp", "Perl", "php", "Python", "Ruby", "Scala", "Scheme" ]; $(function() { $( "#tags" ).autocomplete({ source:sources }); }); </script> <body> <div class="ui-widget"> <h2>查询:<input id="tags"></h2> </div> </body>
{source:sources}将多个sources的String类型数组,包装成JSON.
Ajax服务器端完成:
服务器端网页的Java代码,也只有java代码.
String query = request.getParameter("term");//获取要匹配的参数 String[] sources = {"ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++", "Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran", "Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl", "PHP", "Python", "Ruby", "Scala", "Scheme"}; StringBuilder builder = new StringBuilder("["); for(int i=0;i<sources.length;i++){//遍历目标数组,返回符合条件的结果 if(null != query){ if(sources[i].indexOf(query) >= 0){//表示如果输入了query,sources[i]的String包含String query builder.append("{\\"label\\":\\""+sources[i]+"\\"},");//拼接成{"label":sources[i]}的JSON数据 } }else{//如果不输入query,返回所有的sources[i]成为JSON数组. builder.append("{\\"label\\":\\""+sources[i]+"\\"},"); } } String result = builder.toString();//转换为字符串. if(result.endsWith(",")){//因为拼接的结果转换成字符串后,数组内会多出"," result = result.substring(0,result.length()-1);//需要截去最后一个逗号. } result+="]";//拼接"]" out.print(result);
script:
$(function() { $( "#tags" ).autocomplete({ source:function(request,response){ //request.term估计是将input内容提交后的字符串."term=\'字符串\'",其实等价于传入一个 //{"term":"字符串"}的JSON数据. 具体在jQuery1.11.10的帮助文档中有所描述,搜get第二个即是. $.get("server/demo4_server.jsp","term="+request.term,function(data){ //url(目标地址),data(传入数据),callback(回调函数) var result = $.parseJSON(data); response(result);// 输出返回结果 }); } }); });
parseJSON(String strJSON)函数:
以上是关于[easyUI] autocomplete 简单自动完成以及ajax从服务器端完成的主要内容,如果未能解决你的问题,请参考以下文章
jQuery ui autocomplete 与easyUI冲突解决办法(重命名ui的autocomplete 和menu部分)