• 推荐
  • 评论
  • 收藏

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

2022-11-13    4564次浏览

最近在项目中用到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>  
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);  
            }  
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;  
   }  
原文地址:https://www.cnblogs.com/Leo_wl/p/1997342.html