---
title: "jQuery中对异步提交JSON和XML数据的处理方式"
author: "yaofeng911"
date: "2009-03-23T23:22:54Z"
tags: ["Ajax", "XML", "jQuery", "json", "数据结构"]
slug: "jquery-json-xml"
draft: false
lastmod: "2009-03-25T13:16:01Z"
id: 353860
url: "https://yaofeng911.iteye.com/blog/353860"
---

最近在项目中用到Jquery，感觉真的不错，开源的插件也比较多。 项目中，我随手记录一些常用的方法。也是刚刚学习，有问题大家一起讨论， 希望能留下宝贵意见！ 首先，在JQuery中AJAX请求一般有 $.post(url,data,callback) $.get(url,data,callback) $.ajax (options)... 以post为例JSON数据处理方式： \[img]/upload/attachment/87362/7483e332-1e89-3d85-b388-315874f25327.jpg\[/img] 1. html code: \[code="html"]

exporting...

\[/code] 2.jQuery code: \[code="javascript"] $('#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'); }) });\[/code] 3.由post url执行的action. java code \[code="java"] @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() &lt;= 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] &lt;= 0) { MessageUtils.outputJSONResult("errorimport", response); } Map map = new HashMap(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(); } } } \[/code] XML处理方式： \[img]/upload/attachment/87366/883e9bad-9411-3bb6-8d13-f9d46cdb261b.jpg\[/img] 1.html代码 （用的是jmesa第三包完成页面table的封装，它的功能很强大，正在学习中.. \[code="html"]

${html}

importing...

\[/code] 2. jQuery 代码 \[code="javascript"] 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); } \[/code] 3.java代码 \[code="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() &lt;= 0) { MessageUtils.outputJSONResult("errornull", response); throw new IllegalArgumentException("file error!"); } //parse sdfile to Map object Map 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 sdfMap, final HttpServletRequest request) { //failed to parse file if (sdfMap == null || sdfMap.size() &lt;= 0) { return null; } //get parsed result List&gt; sdfList = (List&gt;) 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 results = new ArrayList(); for (Map 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("![](%5C%22%22+request.getContextPath%28%29+%22/importinfo/structureImage.do?rowcount=%22%20rowcount%20%22%5C%22%2F)"); html.aEnd(); return html.toString(); }}); return tableFacade.render(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } return null; } \[/code] 未完待续...