日期:2014-05-16  浏览次数:20395 次

jqGrid ajax 互搞,json object 互搞
今天玩了玩jqGrid,贴点代码出来,以后方便copy
jqGrid 编辑模式,如果想要编辑,切记cellEdit地方的设置,少了这个,表格死也不能编辑,害老夫郁闷了很久:
jQuery("#table").jqGrid({ 	 
			datatype: "json", 
			width:1019,
			colNames:['编号','名称'], 
			colModel:[ 
			   {name:'no',index:'no', width:15, editable:false},
			   {name:'name',index:'name', width:15, sortable:false,editable: true}
			], 
			multiselect: false,
			cellEdit:true, 
			cellsubmit:"clientArray",
			caption: "数据列表" ,
			onSelectRow: function(ids) {
				s=ids;
			}
		}); 

按钮提交上面这个表单的时候,注意使用POST,GET如果参数过长会被截掉
取得JQGRID中所有数据的代码:
function getFormJosn(){
		var tmp=[];
		var Data="";
		$("#table>tbody>tr").each(function (){
		 tmp[this.id] = "{'no':'"+$("#table").getRowData(this.id).no+"',";
		 tmp[this.id] += "'name':'"+$("#table").getRowData(this.id).name+"'}";
        }); 
		for(var n =0;n<tmp.length;n++){
			Data+=tmp[n];
			Data+=",";
		}
		return {'Data':Data}; 
	}

ajax 将上面的数据传入后台进行业务处理
//保存
		$("#doSave").click(function(){	
			var Data="";
			Data= getFormJosn();
			$.ajax({
				 type: 'POST',
				 url:"xxxx.action?doSave", 
				 data: Data,
				 success:function(data){	
						 alert("over"); 
				}			
			});	 
		});

在补充个JSON互转的代码
public class JsonProvider {
	public static String writeToString(Object object){
		String result ="";
		try {
	    	ObjectMapper m = new ObjectMapper();
			result =m.writeValueAsString(object);
		} catch (JsonGenerationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result ;
	}
	

	public static TypeData fromJSON(String json, TypeData clazz) {
		ObjectMapper mapper = new ObjectMapper();
		try {
			clazz=  mapper.readValue(json, TypeData.class);
		} catch (JsonGenerationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return clazz;
	}
	 public static void main(String[] args) {
		 //resolveJson();
		 String json="{\"name\":\"张三\",\"年龄\":\"15\"}";
		 fromJSON(json,new TypeData());
	}
}