jquery -autocomplete(jquery 自动补全)

编程技术  /  houtizong 发布于 3年前   74

项目中,通常会有输入框联想输入的需求,下面是根据jquery-autocomplete组件封装的一个自动补全插件
依赖:1.0   jquery.js 

           2.0  jquery.autocomplete.js

           3.0  jquery.autocomplete.css

 

ajax请求后台数据,并为输入框绑定 autocomplete事件(封装好的js,在页面可以直接引用):

/* * author:changp * ajax请求后台,初始化数据 *//*定义对象*/var Command = function(inputId,url) {this.inputId = inputId;this.url = url;};/*向后端获取数据*/Command.prototype.execute = function() {var cmdObj = this;/*申明ajax对象*/var xhr = null;var url = this.url;var arr = [];for ( var pro in cmdObj) {var obj = cmdObj[pro];var value = obj;if ($.isArray(obj)) {value = obj.join(",");}if (obj && obj.type == "date") {value = obj.toString();}if ($.isPlainObject(obj) || $.isFunction(obj) || pro == "inputId" || pro == "url") {continue;}arr.push(pro + "=" + encodeURIComponent(value));}var param = arr.join('&');if (window.XMLHttpRequest) {xhr = new XMLHttpRequest();} else {xhr = new ActiveXObject("Microsoft.XMLHTTP.1.0");}xhr.open("POST", url, false);xhr.onreadystatechange = function() {if (xhr.readyState == 4 && xhr.status == 200) {var txt = xhr.responseText;cmdObj.data = eval('('+txt+')');}};xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");xhr.send(param);};/*自动补全*/Command.prototype.autocomplete = function(){var cmdObj = this;$('#'+cmdObj.inputId).autocomplete(cmdObj.data, {        max: 100,                //列表里的条目数        minChars: 0,            //自动完成激活之前填入的最小字符        width: 200,             //提示的宽度,溢出隐藏        scrollHeight: 400,      //提示的高度,溢出显示滚动条        matchContains: true,    //包含匹配,就是data参数里的数据,是否只要包含文本框里的数据就显示        delay: 10,//Default: 远程为400 本地10         autoFill: false,        //自动填充        formatItem: function(row, i, max) {  //列表显示        return cmdObj.formatItem(row, i, max);        },        formatMatch: function(row, i, max) { //匹配对比内容            return cmdObj.formatMatch(row, i, max);        },        formatResult: function(row) { //匹配选择结构            return cmdObj.formatResult(row);        }    }).result(function(event, row, formatted) { //选择完成之后回调函数    cmdObj.result(event, row, formatted);    });};

 


页面调用实例:

 

<!DOCTYPE HTML ><html><head><title>jquery.autocomplete.js 实例</title>   <script type="text/javascript" src="jquery.js"></script><script type='text/javascript' src='jquery.autocomplete.js'></script><script type='text/javascript' src='ajax.autocomplete.js'></script><link rel="stylesheet" type="text/css" href="jquery.autocomplete.css" /></head><body>    <form id="form1">    <div>  用户名称:<input id="name" style="width:200px"/>  购买记录 :<input id="shipcode" style="width:200px"/>    </div>    </form>     <script type="text/javascript">        var cmd = new Command("name","./jsonAction");        cmd.name="changpan";        cmd.pwd = "123456";        cmd.execute();//加载数据后台数据        cmd.autocomplete(); //自动补全        cmd.formatItem = function(row, i, max){//为每个要显示的项目使用高级标签        if("undefined" != typeof row.name || "undefined" != typeof row.to ){               return "<table width='150px'><tr><td align='left'>" + row.name + "</td><td align='right'><font style='color: #009933; font-family: 黑体; font-style: italic'>约【<font color='red'>" + row.to + "</font>】条记录</font></td></tr></table>";            }        };        cmd.formatMatch = function(row, i, max){//对每一行数据使用此函数格式化需要查询的数据格式. 返回值是给内部搜索算法使用的        return row.name;        };        cmd.formatResult = function(row){//和formatItem类似,但可以将将要输入到input文本框内的值进行格式化        //return row.name;        };        cmd.result = function(event, row, formatted){ //选择完毕之后执行的动作        $("#shipcode").val(row.to);        };    </script></body></html>

 

 

后台servlet 代码,返回联想输入列表:

 

package  com.cheese.framework.web;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import net.sf.json.JSONArray;public class JsonAction extends HttpServlet {private static final long serialVersionUID = 1L;public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doPost(request, response);}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {        JSONArray array = new JSONArray();        array.add("{name: \"pingg\", to: \"1\" }");        array.add("{name: \"pingg\", to: \"2\" }");        array.add("{name: \"pingg\", to: \"3\" }");        array.add("{name: \"pingg\", to: \"4\" }");        array.add("{name: \"wang tao\", to: \"2\" }");        array.add("{name: \"changpan\", to: \"3\" }");        array.add("{name: \"yang tingting\", to: \"4\"}");        array.add("{name: \"li an\", to: \"5\" }");        array.add("{name: \"lin la\", to: \"6\" }");        array.add("{name: \"simon\", to: \"7\" }");        array.add("{name: \"xu mei\", to: \"8\" }");response.getWriter().write(array.toString());}}

 

 

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!

留言需要登陆哦

技术博客集 - 网站简介:
前后端技术:
后端基于Hyperf2.1框架开发,前端使用Bootstrap可视化布局系统生成

网站主要作用:
1.编程技术分享及讨论交流,内置聊天系统;
2.测试交流框架问题,比如:Hyperf、Laravel、TP、beego;
3.本站数据是基于大数据采集等爬虫技术为基础助力分享知识,如有侵权请发邮件到站长邮箱,站长会尽快处理;
4.站长邮箱:[email protected];

      订阅博客周刊 去订阅

文章归档

文章标签

友情链接

Auther ·HouTiZong
侯体宗的博客
© 2020 zongscan.com
版权所有ICP证 : 粤ICP备20027696号
PHP交流群 也可以扫右边的二维码
侯体宗的博客