论坛首页 Web前端技术论坛

jQuery中对异步提交JSON和XML数据的处理方式

浏览 19199 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2009-03-23   最后修改:2009-03-25
  最近在项目中用到Jquery,感觉真的不错,开源的插件也比较多。
  项目中,我随手记录一些常用的方法。也是刚刚学习,有问题大家一起讨论,
  希望能留下宝贵意见!
   首先,在JQuery中AJAX请求一般有
   $.post(url,data,callback)  $.get(url,data,callback) 
   $.ajax  (options)...
  以post为例JSON数据处理方式:

1. html code:
 
<div id="export" style="position:absolute;z-index:auto;display: none">
				<input id="exportPath" type="file"/>
		 		<input type="button" id="exportOK" value="OK"/>
		 		<input type="button" id="exportCancel" value="Cancel"/>
		 		<span>exporting...</span>
	  </div>

2.jQuery code:
 
  $('#OK').click(
		function(){
			$('#import span').show();
			$.post(
				path+"/importinfo/importFile.do",
				{filePath:$('#filePath').val()},
				function(data) {
					if ("error" == data) {
						$('#import span').hide();
						jAlert('warning','please select sdFile!','warning');   
						return;
					}
					if ("errornull" == data) {
						$('#import span').hide();
						jAlert('error','the sdfile cannot be empty!','error'); 
						return;
					}
					if ("errorimport" == data) {
						$('#import span').hide();
					    jAlert('error','import error!','error'); 
						return;
					}
					$('#import').hide('normal');
					var da =eval(data);
					var msg ='all num: ' + da[0]["all"] + ';  imported num:' + da[0]["imported"] + ';  failed num: '+ da[0]["failed"];
					jAlert('success',msg,'success');
			})
	});

3.由post url执行的action. java code
	@RequestMapping
	public void importFile(@RequestParam("filePath")
	String filePath, String isDuplicate, String isHaltOnError, String isEmpty,
			HttpServletResponse response) {

		logger.info("preview sdfile action....");
		if (StringUtils.isEmpty(filePath)
				|| !"sdf".equalsIgnoreCase(StringUtils.substringAfterLast(
						filePath, "."))) {
			MessageUtils.outputJSONResult("error", response);
			throw new IllegalArgumentException("cant not find sdf file.");
		}

		File inputFile = new File(filePath);
		if (!inputFile.isFile() || inputFile.length() <= 0) {
			MessageUtils.outputJSONResult("errornull", response);
			throw new IllegalArgumentException("file error!");
		}

		ImporterCondition ic = new ImporterCondition();
		ic.setAllowDuplicate(true);
		ic.setHaltOnError(true);
		ic.setEmptyStructuresAllowed(false);
		int[] rs = compoundService.batchRegister(inputFile, ic);
		if (rs[1] <= 0) {
			MessageUtils.outputJSONResult("errorimport", response);
		}
		Map<String, String> map = new HashMap<String, String>(3);
		map.put("all", String.valueOf(rs[1]));
		map.put("imported", String.valueOf(rs[0]));
		map.put("failed", String.valueOf(rs[2]));
		MessageUtils.outputJSONResult(JSONArray.fromObject(JSONObject.fromObject(map)).toString(), response);//create jsonArray
	}

//MessageUtils.java
public class MessageUtils {
	public static void outputJSONResult(String result, HttpServletResponse response) {
		try {
			response.setHeader("ContentType", "text/json");
			response.setCharacterEncoding("utf-8");
			PrintWriter pw = response.getWriter();
			pw.write(result);
			pw.flush();
			pw.close();

		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void outputXMLResult(String result, HttpServletResponse response) {
		try {
			response.setHeader("ContentType", "xml");
			response.setCharacterEncoding("utf-8");
			PrintWriter pw = response.getWriter();
			pw.write(result);
			pw.flush();
			pw.close();

		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
 


XML处理方式:

1.html代码 (用的是jmesa第三包完成页面table的封装,它的功能很强大,正在学习中..
 <body>
  <input type="hidden" id="filePath" value="${filePath}"/>
		<!-- content-results start -->
		<div id="content-results">
			<c:if test="${not empty html}">
				${html}
			</c:if>
			<p style="text-align: center;">
		 		<input type="button" id="viewOK" value="Import"/>
 				<input type="button" id="viewCancel" value="Cancel" onclick="window.close()"/>
 				<span style="display: none">importing...</span>
 			</p>
		</div>
		<!-- content-results end -->
 
 </body>

2. jQuery 代码
var path='${pageContext.request.contextPath}';
			function onInvokeAction(id) {//解决jmesa分页问题
			    	var parameterString = createParameterStringForLimit(id);
			    	var filePath = $('#filePath').val();
			    	$.post(
			    		path+"/importinfo/preViewSDFJump.do?"+parameterString,
			    		{filePath:filePath},
			    	function(data){
			    		callBackFunction(data);
			    	}
		    	)
		    }
		   
		    function callBackFunction(data){
		    	if("nomatch" == data){
					$("#content-results").html("");
					jAlert('warning', "no data matching!!!!", 'Warning');
					return;
				}
				if("error" == data){
					$("#content-results").html("");
					jAlert('warning', "occur error!", 'Warning');
					return;
				}
				if("nodata" == data){
					jAlert('warning', "Please select the data!", 'Warning');
					return;
				}
				$("#content-results").html(data);
		    }

3.java代码
 @RequestMapping
	public void preViewSDFJump(@RequestParam("filePath")String filePath, 
			HttpServletResponse response, final HttpServletRequest request) throws IOException{
    	logger.info("preview sdfile jump action....");
		if (StringUtils.isEmpty(filePath)|| !"sdf".equalsIgnoreCase(StringUtils.substringAfterLast(filePath, "."))) {
			MessageUtils.outputJSONResult("error", response);
			throw new IllegalArgumentException("cant not find sdf file.");
		}
 
		File inputFile = new File(filePath);
		if (!inputFile.isFile() || inputFile.length() <= 0) {
			MessageUtils.outputJSONResult("errornull", response);
			throw new IllegalArgumentException("file error!");
		}

		//parse sdfile to Map object
		Map<String,Object> sdfMap = ParseSDFileUtil.parseSDF(inputFile);
		//trans result map to html
		String html = this.translatetoHtml(sdfMap, request);
		
		if(null == html){
			MessageUtils.outputJSONResult("nomatch", response);
			throw new IllegalArgumentException("no data.");
		}
		MessageUtils.outputXMLResult(html, response);
    }

   /**
     * trans object to html
     * @param sdfMap
     * @param request
     * @return
     */
    private String translatetoHtml(Map<String,Object> sdfMap, final HttpServletRequest request) {
    	//failed to parse file
		if (sdfMap == null || sdfMap.size() <= 0) {
			return null;
		}
		
		//get parsed result
		List<Map<String,String>> sdfList = (List<Map<String, String>>) sdfMap.get("result");
		String[] keys = (String[]) sdfMap.get("fields");
		
		//set fields to dynamic class
		DynaClass  structureClass = createBasicDynaClass(keys);
		
		try {
			//set property to dynamic object.
			List<DynaBean> results = new ArrayList<DynaBean>();
			for (Map<String, String> structure : sdfList) {
				DynaBean stru = structureClass.newInstance();
				for (String key : keys) {
					stru.set(key, structure.get(key));
				}
				results.add(stru);
			}
			
			//set sdf objects to session.
			request.getSession().setAttribute("results", results);
			
			//create jmesa objects.
			TableFacade tableFacade = TableFacadeFactory.createTableFacade("structuresTable", request);
			tableFacade.addFilterMatcher(new MatcherKey(Object.class), new StringFilterMatcher());
			tableFacade.setColumnProperties(keys);
			tableFacade.setMaxRows(10);
			tableFacade.setMaxRowsIncrements(10, 20, 30);
			tableFacade.setItems(results);
			HtmlTable table = (HtmlTable) tableFacade.getTable();
			// table.getTableRenderer().setWidth("600px");
			table.getRow().setUniqueProperty("structure");
			HtmlColumn molColumn = table.getRow().getColumn("structure");
			molColumn.setTitle("structure");
			molColumn.setFilterable(false);
			molColumn.setSortable(false);
			molColumn.getCellRenderer().setCellEditor(new CellEditor() {
	            public Object getValue(Object item, String property, int rowcount) {
	            // Object value = new BasicCellEditor().getValue(item, property,
				// rowcount);
	                HtmlBuilder html = new HtmlBuilder();
	                html.append("<img width='140' src=\""+request.getContextPath()+"/importinfo/structureImage.do?rowcount="+rowcount+"\"/>");
	                html.aEnd();
	                return html.toString();
	            }});
				return tableFacade.render();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		}
		return null;
    }


未完待续...
  • 大小: 10.3 KB
  • 大小: 86.4 KB
   发表时间:2009-07-15  
补充:
使用JSONObject.fromObject(map).toString()返回json数据后,到页面上格式为:
{"a":"b","c","d"}的字符串,需要将此字符串转换成为JSON数据,使用eval(data)就会报错,正确的方法是使用:data = eval('('+data+')');就可以取得josn格式的数据。
0 请登录后投票
   发表时间:2009-07-19   最后修改:2009-07-19
jquery支持直接操作json返回数据呀。

$.get/post 以及 $.ajax 都支持json返回格式的定义。比如
jQuery.post(url, [data], [callback], [type]) ,最后这个type你写成json就可以对返回的数据进行如同访问对象一般的直接操作。

比如服务器端返回json数据结构如下:
$r = {state:1, msg:'success', data:'xxxxxx'}
那么在客户端可以直接处理:
$.get(
url,
function(rdata) {
  if (rdata.state > 0 ) {  alert(rdata.msg) }
},
'json');
0 请登录后投票
   发表时间:2009-07-20  
mark35 写道
jquery支持直接操作json返回数据呀。

$.get/post 以及 $.ajax 都支持json返回格式的定义。比如
jQuery.post(url, [data], [callback], [type]) ,最后这个type你写成json就可以对返回的数据进行如同访问对象一般的直接操作。

比如服务器端返回json数据结构如下:
$r = {state:1, msg:'success', data:'xxxxxx'}
那么在客户端可以直接处理:
$.get(
url,
function(rdata) {
  if (rdata.state > 0 ) {  alert(rdata.msg) }
},
'json');


简单的JSON数据返回是没有必要用jsonObject处理,如果你需要将一个或多个object组装成json格式是比较麻烦,比如:我需要将List<User>这个集体合做为josn数据传递.
0 请登录后投票
   发表时间:2009-07-20  
yaofeng911 写道
mark35 写道
jquery支持直接操作json返回数据呀。

$.get/post 以及 $.ajax 都支持json返回格式的定义。比如
jQuery.post(url, [data], [callback], [type]) ,最后这个type你写成json就可以对返回的数据进行如同访问对象一般的直接操作。

比如服务器端返回json数据结构如下:
$r = {state:1, msg:'success', data:'xxxxxx'}
那么在客户端可以直接处理:
$.get(
url,
function(rdata) {
  if (rdata.state > 0 ) {  alert(rdata.msg) }
},
'json');


简单的JSON数据返回是没有必要用jsonObject处理,如果你需要将一个或多个object组装成json格式是比较麻烦,比如:我需要将List<User>这个集体合做为josn数据传递.


你可以试用一下 Nutz.Json, 这里是项目首页 http://nutz.googlecode.com/
Nutz.Json 可以将 Java 对象转换成JSON字符串或者加入输出流,它也可以从JSON格式的字符串或者是输入流中获取一个 Java 对象
比如

Person p = Json.fromJson(Person.class,"{id=1,name='333'}");
p.setName("Peter");
System.out.println(Json.toJson(p));

1 请登录后投票
   发表时间:2009-07-20  
对于容器类,无论是 Map,还是 Collection 甚至数组,Nutz.Json 都能正确的转换和输出
0 请登录后投票
   发表时间:2009-07-21  
yaofeng911 写道


简单的JSON数据返回是没有必要用jsonObject处理,如果你需要将一个或多个object组装成json格式是比较麻烦,比如:我需要将List<User>这个集体合做为josn数据传递.


对java不了解。个人看法只要对象能被序列化就能作为json格式传输,客户端操作json对象就如同操作数组一般。
0 请登录后投票
   发表时间:2009-07-21  
mark35 写道
yaofeng911 写道


简单的JSON数据返回是没有必要用jsonObject处理,如果你需要将一个或多个object组装成json格式是比较麻烦,比如:我需要将List<User>这个集体合做为josn数据传递.


对java不了解。个人看法只要对象能被序列化就能作为json格式传输,客户端操作json对象就如同操作数组一般。


你说的没错。呵呵。thanks!
0 请登录后投票
论坛首页 Web前端技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics