Ext.form.field.ComboBox结合Servlet、JSON实现AutoComplete

     这是一个利用Ext.form.field.ComboBox实时获取数据的例子,这个combo必须是可以编辑的,在编辑的过程中通过输入的关键词去后台获取相关的数据。由于combo在自身的代码实现中已经实现了autocomplete的功能,只不过没有着重的表达出来,不过我们还是还是可以通过代码挖掘出来。这个是从一个官方的例子衍生而来的,官方的例子还是很全面的。下面我们看具体实现,前端JS代码:
Ext.onReady(function() {

	Ext.define("Resource", { //定义一个数据模型
				extend : 'Ext.data.Model',
				fields : [{
							name : 'text',
							mapping : 'text'
						}, {
							name : 'iconCls',
							mapping : 'iconCls'
						}]
			});

	ds = Ext.create('Ext.data.Store', { //定义数据源
				model : 'Resource',
				proxy : {
					type : 'ajax',
					url : 'autocomplete', //获取数据的路径
					reader : {
						type : 'json',
						root : 'root',
						totalProperty : 'total'
					}
				}
			});

	panel = Ext.create('Ext.panel.Panel', {
		renderTo : Ext.getBody(),
		title : '查找资源',
		width : 600,
		bodyPadding : 10,
		layout : 'anchor',
		items : [{
			xtype : 'combo',
			store : ds,
			displayField : 'text',
			typeAhead : false,
			hideLabel : true,
			hideTrigger : true,
			anchor : '100%',
			minChars : 1, //定义输入最少输入多少个字符的时候获取数据
			listConfig : {
				emptyText : '<div style="line-height:22px;padding:2px 10px">没有找到匹配的数据</div>',
				getInnerTpl : function() { //通过数据模型定义的内容,自定义展示内容
					return '<div class="search-item" >'
							+ '<div class="x-tree-icon x-tree-icon-leaf search-item-icon  {iconCls}"></div>'
							+ '{text}' + '</div>'
				}
			}
		}, {
			xtype : 'component',
			style : 'margin-top:10px',
			html : '输入关键词,实时查找后台数据。'
		}]
	});
});

     后台Java代码:
request.setCharacterEncoding("UTF-8");
		String query = request.getParameter("query"); //关键词默认参数名是query,如果需要自定义可以在combo配置
		//通过模糊查询获取数据,这里只是粗略的处理。其实整个功能这里才是最精细和关键的,如处理拼音的问题
		List<JSONObject> list = BaseDAO.findBySql("select t.text,t.iconCls " 
				+ " from resource t " + " where t.text like '%" + query.trim() + "%'");
		PageWriter.output(list, response);
     输出的数据格式是JSON, 在传递中文的时候,注意tomcat或其他应用服务器对于中文的处理。
   QQ讨论群:197331959, http://www.hatustudio.com  Leetop/Ext项目论坛
   http://download.csdn.net/detail/leecho571/4343627 实例下载,里面有个app.sql的数据库文件,用mysql数据库导入即可

猜你喜欢

转载自blog.csdn.net/leecho571/article/details/7621680