现在的位置: 首页 > 综合 > 正文

extjs4 grid 新增、删除、修改

2017年10月15日 ⁄ 综合 ⁄ 共 7903字 ⁄ 字号 评论关闭

删除与修改的操作,分两块进行。页面删除与后台删除。因此在页面上进行删除或修改后成功后,后台只传递一个SUCCESS标记,若后台同步成功,则在页面的store中执行删除或者修改。减少网络中的数据传输。

但是这样有一个bug,就是当用户新增了幻影数据,并且与真实数据一起修改填写提交后,后台已经写入数据库。然后此时再删除之前添加的幻影数据,会导致id(代表一条记录的主键,本文代码中是userId)传递不到后台,导致无法查询删除。解决方案是当后台处理成功后,前台重新加载页面,但是这样网络负担就加重了。使之前的优势丧失

Ext.onReady(function() {
	Ext.define('User', {
				extend : 'Ext.data.Model',
				fields : [{
							name : 'userId',
							type : 'int',
							useNull : true//这样数字如果值为空则不会自动转成0,则提交时注意后台bean类中的属性int要用对象类型,否则解析出错
						}, {
							name : 'loginName',
							type : 'string'
						}, {
							name : 'password',
							type : 'string'
						}, {
							name : 'remark',
							type : 'string'
						}, {
							name : 'roleId',
							type : 'float',
							useNull : true
						}, {
							name : 'rightId',
							type : 'float',
							useNull : true
						}, {
							name : 'platformNo',
							type : 'string'
						}, {
							name : 'groupId',
							type : 'float',
							useNull : true
						}, {
							name : 'net',
							type : 'string'
						}, {
							name : 'email',
							type : 'string'
						}, {
							name : 'linkman',
							type : 'string'
						}, {
							name : 'tel',
							type : 'string'
						}, {
							name : 'fax',
							type : 'string'
						}, {
							name : 'address',
							type : 'string'
						}],
				idProperty : 'userId'// 极为重要的配置。关系到表格修改数据的获取
			});

	var store = new Ext.data.Store({
				model : 'User',
				pageSize : 3,
				proxy : {
					type : 'ajax',
					url : 'baseUsers.action',
					reader : {
						type : 'json',
						root : 'pageBean.list',
						totalProperty : 'pageBean.total'
					}
				},
				autoLoad : false
			});
	var cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
				clicksToEdit : 2
			});
	var grid = Ext.create('Ext.grid.Panel', {
		tbar : [ {
					xtype : 'button',
					text : '新增',
					handler : add
				},{
					xtype : 'button',
					text : '提交修改',
					handler : alter
				}, {
					xtype : 'button',
					text : '删除',
					handler : otherDelete
				}],
		title : 'All Products',
		store : store,
		columnLines : true,
		selModel : Ext.create('Ext.selection.CheckboxModel'),
		columns : [{
					header : 'userId',
					dataIndex : 'userId',
					hidden:true
				}, {
					header : 'loginName',
					dataIndex : 'loginName',
					editor : {
						allowBlank : false
					}
				}, {
					header : 'password',
					dataIndex : 'password',
					editor : {
						allowBlank : false
					}
				}, {
					header : 'remark',
					dataIndex : 'remark',
					editor : {
						allowBlank : false
					}
				}, {
					header : 'roleId',
					dataIndex : 'roleId',
					editor : {
						allowBlank : false
					}
				}, {
					header : 'rightId',
					dataIndex : 'rightId',
					editor : {
						allowBlank : false
					}
				}, {
					header : 'platformNo',
					dataIndex : 'platformNo',
					editor : {
						allowBlank : false
					}
				}, {
					header : 'groupId',
					dataIndex : 'groupId',
					editor : {
						allowBlank : false
					}
				}, {
					header : 'net',
					dataIndex : 'net',
					editor : {
						allowBlank : false
					}
				}, {
					header : 'email',
					dataIndex : 'email',
					editor : {
						allowBlank : false
					}
				}, {
					header : 'linkman',
					dataIndex : 'linkman',
					editor : {
						allowBlank : false
					}
				}, {
					header : 'tel',
					dataIndex : 'tel',
					editor : {
						allowBlank : false
					}
				}, {
					header : 'fax',
					dataIndex : 'fax',
					editor : {
						allowBlank : false
					}
				}, {
					header : 'address',
					dataIndex : 'address',
					editor : {
						allowBlank : false
					}
				}],

		forceFit : true,
		dockedItems : [{
					xtype : 'pagingtoolbar',
					store : store, // same store GridPanel is
					// using
					dock : 'bottom',
					displayInfo : true
				}],
		renderTo : 'userMngDiv',
		plugins : [cellEditing]
			// autoRender:true
		});
	store.loadPage(1);
	var p = parent.Ext.getCmp('contentTabs');
	// alert(p);
	function alter() {
		var records = store.getUpdatedRecords();// 获取修改的行的数据,无法获取幻影数据
		var phantoms=store.getNewRecords( ) ;//获得幻影行
		records=records.concat(phantoms);//将幻影数据与真实数据合并
		if (records.length == 0) {
			Ext.MessageBox.show({
				title : "提示",
				msg : "没有任何数据被修改过!"
					// icon: Ext.MessageBox.INFO
				});
			return;
		} else {
			Ext.Msg.confirm("请确认", "是否真的要修改数据?", function(button, text) {
				if (button == "yes") {
					var data = [];
					// alert(records);
					Ext.Array.each(records, function(record) {
						data.push(record.data);
							// record.commit();// 向store提交修改数据,页面效果
						});

					Ext.Ajax.request({
						url : 'alterUsers.action',
						params : {
							alterUsers : Ext.encode(data)
						},
						method : 'POST',
						timeout : 2000,

						success : function(response, opts) {
							var success = Ext.decode(response.responseText).success;
							// 当后台数据同步成功时
							if (success) {
								Ext.Array.each(records, function(record) {
											// data.push(record.data);
											record.commit();// 向store提交修改数据,页面效果
										});
							} else {
								Ext.MessageBox.show({
									title : "提示",
									msg : "数据修改失败!"
										// icon: Ext.MessageBox.INFO
									});
							}
						}
					});
				}
			});

		}

	}
	// 传递对象删除
//	function deleteUsers() {
//		var data = grid.getSelectionModel().getSelection();
//		// alert(data);
//		if (data.length == 0) {
//			Ext.MessageBox.show({
//				title : "提示",
//				msg : "请先选择您要操作的行!"
//					// icon: Ext.MessageBox.INFO
//				});
//			return;
//		} else {
//			Ext.Msg.confirm("请确认", "是否真的要删除数据?", function(button, text) {
//				if (button == "yes") {
//					var ids = [];
//					Ext.Array.each(data, function(record) {
//								ids.push(record.data);
//							});
//					Ext.Ajax.request({
//						url : 'deleteUsers.action',
//						params : {
//							deleteUsers : Ext.encode(ids)
//						},
//						method : 'POST',
//						// timeout : 2000,//默认30秒
//						success : function(response, opts) {
//							var success = Ext.decode(response.responseText).success;
//							// 当后台数据同步成功时
//							if (success) {
//								Ext.Array.each(data, function(record) {
//											store.remove(record);// 页面效果
//										});
//							} else {
//								Ext.MessageBox.show({
//									title : "提示",
//									msg : "数据删除失败!"
//										// icon: Ext.MessageBox.INFO
//									});
//							}
//
//						}
//					});
//				}
//			});
//
//		}
//	}
	// 编码ID删除
	function otherDelete() {

		var data = grid.getSelectionModel().getSelection();
		// alert(data);
		if (data.length == 0) {
			Ext.MessageBox.show({
				title : "提示",
				msg : "请先选择您要操作的行!"
					// icon: Ext.MessageBox.INFO
				});
			return;
		} else {
			Ext.Msg.confirm("请确认", "是否真的要删除数据?", function(button, text) {
				if (button == "yes") {
					var ids = [];
					Ext.Array.each(data, function(record) {
								var userId=record.get('userId');
								//如果删除的是幻影数据,则id就不传递到后台了,直接在前台删除即可
								if(userId){
									ids.push(userId);
								}
								
							});

					Ext.Ajax.request({
						url : 'deleteUsers.action',
						params : {
							deleteIds : ids.join(',')
						},
						method : 'POST',
						// timeout : 2000,//默认30秒
						success : function(response, opts) {

							// store.loadPage(1);

							var success = Ext.decode(response.responseText).success;
							// 当后台数据同步成功时
							if (success) {
								Ext.Array.each(data, function(record) {
											store.remove(record);// 页面效果
										});
							} else {
								Ext.MessageBox.show({
									title : "提示",
									msg : "数据删除失败!"
										// icon: Ext.MessageBox.INFO
									});
							}

						}
					});
				}
			});

		}

	}
	function add(){
		store.insert(0,new User());
	}
});
package wk.len.actions.system;
import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


import wk.len.beans.PageBean;
import wk.len.po.BaseUsers;


import com.opensymphony.xwork2.ActionSupport;

public class UsersAction extends ActionSupport {
	private PageBean pageBean;
	private int start;
	private int limit;
	private String alterUsers;
	private String deleteIds;
	private boolean success;
	
	public String usersInfo() throws Exception {
		int end = start + limit;
		if(end>86)
			end=86;
		List<BaseUsers> list = new ArrayList<BaseUsers>();
		for (int i = start; i <end; i++) {
			BaseUsers p=new BaseUsers();
			p.setUserId(i);
		list.add(p);
		}
		int totalProperty=86;
		pageBean=new PageBean(list,totalProperty); 
		success=true;//若没有,grid会取不到数据。或者干脆就不要有success这个标记,这样grid默认就能取出数据了
		return SUCCESS;
	}
	
	public String deleteUsers(){

		 
//		  JSONArray array = JSONArray.fromObject(deleteUsers); 
//		  List<BaseUsers> obj = new ArrayList<BaseUsers>(); 
//		  for(int i = 0; i < array.size(); i++){ 
//		  JSONObject jsonObject = array.getJSONObject(i); 
//		  obj.add((BaseUsers) JSONObject.toBean(jsonObject, BaseUsers.class)); 
//		  } 
		  System.out.println(deleteIds);
		  String[]Ids=deleteIds.split(",");//传递到数据库的参数
		  System.out.println(Ids[0]);
		 // System.out.println(obj.get(0).getEmail());
		  success=true;//需要后台数据库修改成功后传递该值
		  return SUCCESS;
	}
	public String alterUsers(){
		  JSONArray array = JSONArray.fromObject(alterUsers); 
		  List<BaseUsers> alertUsers = new ArrayList<BaseUsers>(); //传递到数据库修改的参数
		  for(int i = 0; i < array.size(); i++){ 
		  JSONObject jsonObject = array.getJSONObject(i); 
		  alertUsers.add((BaseUsers) JSONObject.toBean(jsonObject, BaseUsers.class)); 
		  }
		 // System.out.println(alertUsers);
		  success=true;//需要后台数据库修改成功后传递该值
		  return SUCCESS;
	}
	public PageBean getPageBean() {
		return pageBean;
	}

	public void setPageBean(PageBean pageBean) {
		this.pageBean = pageBean;
	}

	public int getStart() {
		return start;
	}

	public void setStart(int start) {
		this.start = start;
	}

	public int getLimit() {
		return limit;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}



	public String getAlterUsers() {
		return alterUsers;
	}

	public void setAlterUsers(String alterUsers) {
		this.alterUsers = alterUsers;
	}

	public boolean isSuccess() {
		return success;
	}

	public void setSuccess(boolean success) {
		this.success = success;
	}

	public String getDeleteIds() {
		return deleteIds;
	}

	public void setDeleteIds(String deleteIds) {
		this.deleteIds = deleteIds;
	}



}

struts2配置

<struts>
	<package name="system" extends="json-default" namespace="/">
		<action name="baseUsers" class="wk.len.actions.system.UsersAction" method="usersInfo">
			<result name="success" type="json">
				
			</result>
		</action>
		<action name="deleteUsers" class="wk.len.actions.system.UsersAction" method="deleteUsers">
			<result name="success" type="json">
				<param name="includeProperties">success</param>
			</result>
		</action>
		<action name="alterUsers" class="wk.len.actions.system.UsersAction" method="alterUsers">
			<result name="success" type="json">
				<param name="includeProperties">success</param>
			</result>
		</action>
	</package>
</struts>    

抱歉!评论已关闭.