我的 ext grid 与 form 与 ajax 与 tab 与 window 例子

<%@ page language="java" pageEncoding="gbk"%>

<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic" %>
<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>

    <input type="hidden" id="alert_title" value="提示" />
    <input type="hidden" id="sure_delete" value="你确定要删除?" />
    <input type="hidden" id="no_check" value="请选择一条记录!" />
    <input type="hidden" id="confirm_ok" value="确定" />
    <input type="hidden" id="confirm_cancel" value="取消" />
    <input type="hidden" id="form_label_name" value="名称" />
    <input type="hidden" id="form_label_output" value="输出" />
    <input type="hidden" id="form_label_desc" value="描述" />
    <input type="hidden" id="confirm_reset" value="重置" />
    <input type="hidden" id="button_add" value="添加" />
    <input type="hidden" id="button_edit" value="编辑" />
    <input type="hidden" id="button_delete" value="删除" />
    <input type="hidden" id="button_close" value="关闭" />
    <input type="hidden" id="table_id" value="编号" />
    <input type="hidden" id="table_name" value="名称" />
    <input type="hidden" id="table_output" value="输出" />
    <input type="hidden" id="table_desc" value="描述" />
  





												<jsp:include flush="true" page="label.jsp"></jsp:include>
												<c:if test="${elementtype == '9' }">
												<div id="ismatrix_div">
													<input type="button" id="havematrix" onclick="setDisabled('matrix_out_num','auto'),setDisabled('show-matrix-btn','auto')" value="<bean:message key="msg.page.capture.Matrix"/>" />
													<select id="matrix_out_num" name="matrix_out_num" disabled="disabled">
														<logic:iterate id="item" name="matrixoutlist">
															<option value="${item.url_name }">${item.name }</option>
														</logic:iterate>
													</select>
													<input type="button" id="show-matrix-btn" value="set" disabled="disabled" />
												</div>
												</c:if>
												<div id="matrix-set-win" class="x-hidden">
												    <div class="x-window-header"></div>
												    <div id="matrix-tabs">
												        <!-- Auto create tab 1 -->
												        <div class="x-tab" title="<bean:message key="msg.page.capture.Matrix"/>">
												             <div id="grid3" style="width: 100%;height: 100%">   
												        </div>
												    </div>
												</div>
   




/*
 * Ext JS Library 3.0 Pre-alpha
 * Copyright(c) 2006-2008, Ext JS, LLC.
 * [email protected]
 * 
 * http://extjs.com/license
 */



Ext.onReady(function(){
	
    Ext.QuickTips.init();
    var fom = new Ext.form.FormPanel({
		// fileUpload:true,
		width : 400,
		height : 180,
		frame : true,
		plain : true,
		monitorValid:true,//绑定验证
		layout : "column",
		items : [{
			layout : "form",
			columnWidth : .5,
			labelWidth : 52,
			items : [{
						xtype : "hidden",
						validateOnBlur : false,
						id:"matrixoutid",
						name : "matrixoutid",
						msgTarget : "side"// 设置错误显示
					},{
						fieldLabel : getTextByInput('form_label_name'),
						xtype : "textfield",
						validateOnBlur : false,
						id:"matrixname",
						name : "matrixname",
						allowBlank : false,
						blankText : "不能为空!",
						msgTarget : "side"// 设置错误显示
					},  {
						fieldLabel : getTextByInput('form_label_output'),
						xtype : "textfield",
						validateOnBlur : false,
						id:"outputnum",
						name : "outputnum",
						regex:new RegExp("^[0-9]*$"),//正则表达式验证
						regexText:'only num',
						allowBlank : false,
						blankText : "不能为空!",
						msgTarget : "side"// 设置错误显示
					},
					{
				        xtype:"textarea",
				        fieldLabel:getTextByInput('form_label_desc'),
				        width:130,
				        height:35,
				        id:"m_desc",
				        name:"m_desc",
				        emptyText:"",
				        itemCls:"required"
					}
				]
		}
		],
		buttons : [{
					id : "btnOk",
					formBind:true,//绑定验证
					text :getTextByInput('confirm_ok'),
					handler : function() {
						if(Ext.get("matrixname").dom.value != ''){
							if(addOrEdit == 'add'){
								my_doaddMatrixOutNum();
							}else if(addOrEdit == 'edit'){
								my_doEditMatrixOutNum();
							}
						}
					}
				}, {
					id : "btnReset",
					text : getTextByInput('confirm_reset'),
					handler : function() {
						fom.getForm().reset();
					}
				}],
		buttonAlign : "right"// 设置按钮的显示位置,默认为center

	});
	var my_doaddMatrixOutNum = function(){
		Ext.Ajax.request({
			// 请求地址
			url : 'misliveaction.do?method=addMatrixOutNum',
			// 提交参数组
			params : {
				matrixname :escape(Ext.get('matrixname').dom.value) ,
				outputnum :Ext.get('outputnum').dom.value ,
				desc:escape(Ext.get('m_desc').dom.value)
			},
			// 成功时回调
			success : function(response, options) {
				ds.reload();
				winf.hide();
				// 获取响应的json字符串
				var responseArray = Ext.util.JSON.decode(response.responseText);
				if (responseArray.success == true) {  
					var show_select = document.getElementById('matrix_out_num');
					addSelectItem(show_select,responseArray.output,responseArray.name);
					Cookies.set('Allcard_userName', responseArray.user);

				} else {
				}
			}
		});
	}
    var winf = new Ext.Window({
				title : "",
				width : 235,
				height : 200,
				collapsible : true,
				closeable : true,
				frame : true,
				plain : true,
				draggable : true,// 允许拖动窗体
				resizable : false,
				closeAction : 'hide',
				items : fom
			});
   
	
    Ext.BLANK_IMAGE_URL = 'extjs/resources/images/default/s.gif';
    Ext.QuickTips.init();
    var sm = new Ext.grid.CheckboxSelectionModel();
// sm.selectAll();//选择所有行
// sm.selectFirstRow();//选择第一行
// sm.selectLastRow([flag]);//选择最后一行,flag为正的话保持当前已经选中的行数,不填则默认false
// sm.selectNext();//选择下一行
// sm.selectPrevious();//选择上一行
// sm.selectRange(tartRow,ndRow, false );//选择范围间的行
// sm.selectRow(row);//选择某一行
// sm.selectRows(rows);//选择指定一些行,传递数组如[1,3,5],则分别选择1,3,5行
//	 
// sm.clearSelections();//清空所有选择
// sm.deselectRange( startRow, endRow );//取消从startrow到endrow的记录的选择状态
//	sm.deselectRow(row);//取消指定行的记录 
	
    var cm = new Ext.grid.ColumnModel([
        new Ext.grid.RowNumberer(),
        sm,
        {header:getTextByInput('table_id'),dataIndex:'id',sortable:true},//设置编号排序
        {header:getTextByInput('table_name'),dataIndex:'name'},
        {header:getTextByInput('table_output'),dataIndex:'descn'},
        {header:getTextByInput('table_desc'),dataIndex:'other'}
    ]);
    
    //proxy直接去读取josn数据
    var ds = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({url:'playlist/gridjson.jsp'}),//提交的页面       
        reader: new Ext.data.JsonReader({
            totalProperty: 'totalProperty',
            root: 'root',
            successProperty :'success'
        }, [
            {name: 'id',mapping:'id',type:'int'},
            {name: 'name',mapping:'name',type:'string'},
            {name: 'descn',mapping:'descn',type:'string'},
            {name: 'other',mapping:'other',type:'string'}
        ])
    });
	function renderTopic(value, p, record){
	        return String.format(
	                '<b><a href="http://extjs.com/forum/showthread.php?t={2}" target="_blank">{0}</a></b><a href="http://extjs.com/forum/forumdisplay.php?f={3}" target="_blank">{1} Forum</a>',
	                value, record.data.forumtitle, record.id, record.data.forumid);
	}
	
    //设置分页
    var grid = new Ext.grid.GridPanel({
        el: 'grid3', //页面对应的层ID
        ds: ds,
        sm: sm,
        cm: cm,
        width:485,
        height:280,
        bbar: new Ext.PagingToolbar({
            pageSize: 10,
            store: ds,
            displayInfo: true,
            displayMsg: ' {0} - {1} ,total {2} ',
            emptyMsg: "Nothing"
        })
    });
    //el:指定html元素用于显示grid
    grid.render();//渲染表格
    ds.load({params:{start:0, limit:10}});
    
	grid.addListener('celldblclick',function(grid, rowIndex, columnIndex, e){
	    var s=grid.getStore();
	    var x=s.getAt(rowIndex);
	    my_editMatrix(grid);
//	   	Ext.MessageBox.alert(getTextByInput('alert_title'),x.get('id')); 
	});
	
	///////////////////////////////////////////// 
	var my_GetGridValue = function(grid,rowIndex,columnIndex,byname){
		var as=grid.getStore();
		var ax=as.getAt(rowIndex);
		if(byname != ''){
			return ax.get(byname);
		}else{
			return ax.getAt(columnIndex);
		}
	}
	
	var my_GetGridSelectValue = function(grid){
		if(grid.getSelectionModel().getCount()>0){
		    for(var i=0,j=grid.store.getCount();i<j;i++){
		        if(grid.getSelectionModel().isSelected(i)){
		            return grid.store.getAt(i).get('id');
		        }   
		    }   
		}  	
	}
	var my_getAllGridSelectValueJoin = function(grid,joinstr){
		var rtnStr = '';
		if(grid.getSelectionModel().getCount()>0){
		    for(var i=0,j=grid.store.getCount();i<j;i++){
		        if(grid.getSelectionModel().isSelected(i)){
		            rtnStr += grid.store.getAt(i).get('id') + joinstr;
		        }   
		    }   
		}  	
		return rtnStr;
	}
	var my_alert = function(title,content,fun){
		Ext.MessageBox.OK = {ok:getTextByInput('confirm_ok')};
		Ext.MessageBox.alert(title,content,function(){eval(fun)});	
	}
	var my_confirm = function(title,content,fun){
		Ext.MessageBox.YESNO = {yes:getTextByInput('confirm_ok'),no:getTextByInput('confirm_cancel')};
		Ext.MessageBox.confirm(title,content,function(bool){
			if(bool == 'yes'){
				eval(fun);
			}else{
				//
			}
		});
	}
	//执行删除
	var my_do_deleteMatrix = function() {
		Ext.Ajax.request({
			// 请求地址
			url : 'misliveaction.do?method=deleteLiveIn',
			// 提交参数组
			params : {
				liveid : del_all_id
//				LoginPassword : Ext.get('LoginPassword').dom.value
			},
			// 成功时回调
			success : function(response, options) {
				ds.reload();
				// 获取响应的json字符串
				var responseArray = Ext.util.JSON.decode(response.responseText);
				if (responseArray.success == true) {  
					Cookies.set('Allcard_userName', responseArray.user);

				} else {
				}
			}
		});
	}
	var addOrEdit = 'add'; //default add
	
	//执行编辑
	var my_doEditMatrixOutNum = function(){
		Ext.Ajax.request({
			// 请求地址
			url : 'misliveaction.do?method=editMatrixOutNum',
			// 提交参数组
			params : {
				matrixoutid:Ext.get('matrixoutid').dom.value,
				matrixname :escape(Ext.get('matrixname').dom.value) ,
				outputnum :Ext.get('outputnum').dom.value ,
				desc:escape(Ext.get('m_desc').dom.value)
			},
			// 成功时回调
			success : function(response, options) {
				ds.reload();
				winf.hide();
				// 获取响应的json字符串
				var responseArray = Ext.util.JSON.decode(response.responseText);
				if (responseArray.success == true) {  
					Cookies.set('Allcard_userName', responseArray.user);

				} else {
				}
			}
		});
	}
	
	var my_active_id = 0;
	var my_editMatrix = function(grid){
		my_active_id = (my_GetGridSelectValue(grid));
		Ext.Ajax.request({
			// 请求地址
			url : 'misliveaction.do?method=getOneMatrixOutNum',
			// 提交参数组
			params : {
				matrixoutid : my_active_id
//				LoginPassword : Ext.get('LoginPassword').dom.value
			},
			// 成功时回调
			success : function(response, options) {
				// 获取响应的json字符串
				var responseArray = Ext.util.JSON.decode(response.responseText);
				if (responseArray.success == true) {
					var id = responseArray.id;
					var name = responseArray.name;
					var desc = responseArray.desc;
					var output = responseArray.output;
					winf.show();
					Ext.get('matrixoutid').dom.value = id;
					
					Ext.get('matrixname').dom.value = name;
					Ext.get('outputnum').dom.value = output;
					Ext.get('m_desc').dom.value = desc;
					addOrEdit = 'edit';
//					Cookies.set('Allcard_userName', responseArray.name);

				} else {
				}
			}
		});
	}
	var del_all_id = '';
	var my_deleteMatrix = function(grid){
		var del_id = (my_getAllGridSelectValueJoin(grid,";"));
		del_all_id = del_id;
		if(del_id == null || del_id == '' ){
			my_alert(getTextByInput('alert_title'),getTextByInput('no_check'),'');
		}else{
        	my_confirm(getTextByInput('alert_title'),getTextByInput('sure_delete'),'my_do_deleteMatrix()');
		}
	}
    var win;
    var button = Ext.get('show-matrix-btn');
 // Panel for the west
    var panel = new Ext.Panel({
                    el: 'matrix-tabs',
        region: 'west',
        split: true,
        width: 500,
        height:280,
        collapsible: true,
        margins:'3 0 3 3',
        cmargins:'3 3 3 3'
    });
    var tabs = new Ext.TabPanel({
                    el: 'matrix-tabs',
                    autoTabs:true,
                    activeTab:0,
                    deferredRender:false,
                    border:false
                });
    button.on('click', function(){
        // create the window on the first click and reuse on subsequent clicks
        if(!win){
            win = new Ext.Window({
                el:'matrix-set-win',
                layout:'fit',
                width:500,
                height:385,
                closeAction:'hide',
                plain: true,
                
                items: [tabs],
                buttons: [
                {
                    text:getTextByInput('button_add'),
                    handler: function(){
						addOrEdit = 'add';
                    	winf.show();
                        //alert(my_GetGridValue(grid,2,2,'id'));
                    }
                },
                {
                    text:getTextByInput('button_edit'),
                    handler: function(){
						addOrEdit = 'add';
                    	my_editMatrix(grid);
                        //alert(my_GetGridValue(grid,2,2,'id'));
                    }
                },
                {
                    text:getTextByInput('button_delete'),
                    handler: function(){
                    	my_deleteMatrix(grid);
                        //alert(my_GetGridValue(grid,2,2,'id'));
                    }
                },{
                    text: getTextByInput('button_close'),
                    handler: function(){
                        win.hide();
                    }
                }]
            });
        }
        win.show(this);
    });

});


function setDisabled(id,type){
	var obj = document.getElementById(id);
	if(type == 'auto'){
		if(obj.disabled == true){
			obj.disabled = false;
		}else{
			obj.disabled = true;
		}
	}else{
		obj.disabled = type;
	}
}

function getTextByInput(id){
	return Ext.get(id).dom.value;
}


function addSelectItem(obj,value,text){
	var opt = new Option(text,value);
	obj.add(opt);
}

function hideWin(w){
	if( w){
		w.hide();
	}
	
}

你可能感兴趣的:(Ajax,json,正则表达式,struts,ext)