zoukankan      html  css  js  c++  java
  • ajax 封装

    1 表单提交方式(ContentType省略:默认为application/x-www-form-urlencoded方式提交)

    /**
     * 封装的方法获取Object数据
     *
     * @param isUrl
     * @param callback
     * @param dataParam
     * @param async 异步请求 非必传 true 异步|false 同步 默认true,
     * @param type 请求类型 非必传 post | get 默认post
     */
    postObjects = function(isUrl, callback, dataParam, async, type) { // dbsecGetObjects
        if (dataParam == null || dataParam == undefined) {
            dataParam = {};
        }
        dataParam.t = Math.random();
        var async = typeof async == "undefined" || (typeof async == "boolean" && async) ? true : false;
        var type = typeof type == "undefined" || (type != "get") ? "post" : "get";
        $.ajax({
            async : async,
            type : type,
            dataType : "json",
            data : dataParam,
            url : isUrl,
            success : function(result) {
                if (typeof callback === "function") {
                    result != null && result != undefined ? callback(result) : callback();
                }
            },
            error : function(xhr, errorText, errorType) {
                // console.log(xhr + "--" + errorText + "--" + errorType);
            }
        });
    }
    

    2.Json方式提交

    /**
     * 封装的方法获取Object数据,参数为json字符串
     *
     * @param isUrl
     * @param callback
     * @param dataParam
     */
    postJson = function(isUrl, callback, dataParam) { // dbsecPostObjects
        if (dataParam == null || dataParam == undefined) {
            dataParam = {};
        }
        var data = {};
        $.each(dataParam,function(i,item){
            data[item.name] = item.value;
        });
        data = JSON.stringify(data)
        data.t = Math.random();
        $.ajax({
            url : isUrl,
            data : data,
            dataType : "json",
            type : "post",
            contentType : "application/json;charset=utf-8",
            async : true,
            success : function(result) {
                if (typeof callback === "function") {
                    result != null && result != undefined ? callback(result) : callback();
                }
            },
            error : function(xhr, errorText, errorType) {
                // console.log(xhr + "--" + errorText + "--" + errorType);
            }
        });
    }
    

    -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    根据如上两个共通方法分析如下:  

    第一种.ContentType: 为 application/x-www-form-urlencoded编码的内容

      tips:后台用@RequestParam(不写默认为RequestParam)

      说明:@RequestParam 底层是通过request.getParameter方式获得参数的,也就是说,@RequestParam 和 request.getParameter是同一回事。所以@RequestParam用来处理Content-Type: 为 application/x-www-form-urlencoded编码的内容,提交方式GET、POST。

      业务js代码如下:  

    function savezdcsEdit(){
    	var url = "";
    	if ($("#saveKbn").val() == "add") {
    		url = serverPath+"/zdcsList/addZdcs";
    	} else if ($("#saveKbn").val() == "edit") {
    		url = serverPath+"/zdcsList/editZdcs";
    	}
        postJson(url, function(obj){
            if (obj.code == "0") {
                swal(obj.message,"","success");
            } else {
                swal(obj.message,"","error");
            }
        },$("#zdcsEditForm").serialize());
    
    };
    

      后台Controller代码

    @RequestMapping(value = "/editZdcs")
    @ResponseBody
    public Map<String,Object> editzdcs(KeyPlaceEntity key){
    	Map<String,Object> ListMap = new HashMap<String, Object>();
    	ListMap.put(Const.RETURN_CODE, Const.STATUS_SUCCESS);
    	ListMap.put(Const.RETURN_MESSAGE, Const.MESSAGE_EDIT_SUCCESS);
    	return ListMap;
    }
    

    tips:再提示一遍.controller中的方法参数默认是@RequestParam 对应为application/x-www-form-urlencoded编码提交

    第二种:第一种.ContentType: 为 application/json编码的内容

      @RequestBody 该注解常用来处理Content-Type: 不是application/x-www-form-urlencoded编码的内容,例如application/json, application/xml等;

      @RequestBody接收的是一个Json对象的字符串,而不是一个Json对象。在ajax请求往往传的都是Json对象,用 JSON.stringify(data)的方式就能将对象变成字符串。

      业务js代码

    function savezdcsEdit(){
    	var url = "";
    	if ($("#saveKbn").val() == "add") {
    		url = serverPath+"/zdcsList/addZdcs";
    	} else if ($("#saveKbn").val() == "edit") {
    		url = serverPath+"/zdcsList/editZdcs";
    	}
        postJson(url, function(obj){
            if (obj.code == "0") {
                swal(obj.message,"","success");
            } else {
                swal(obj.message,"","error");
            }
        },$("#zdcsEditForm").serializeArray());
    
    };
    

      后台Controller代码

    @RequestMapping(value = "/editZdcs")
    @ResponseBody
    public Map<String,Object> editzdcs(@RequestBody  KeyPlaceEntity key){
            Map<String,Object> ListMap = new HashMap<String, Object>();
    	ListMap.put(Const.RETURN_CODE, Const.STATUS_SUCCESS);
    	ListMap.put(Const.RETURN_MESSAGE, Const.MESSAGE_EDIT_SUCCESS);
    	return ListMap;
    }
    

      tips:因为提交方式为Json,so,后台代码需要用Json方式(@RequestBody)去接,要不然,是取不到值滴

  • 相关阅读:
    js字符串函数
    js流程语句
    js数组
    js变量
    js运算符
    Time.deltaTime和Time.realtimeSinceStartup
    Prefabs实例化 ResourceMgr
    SLua
    判断物体是否在摄像机内
    [Unity3D]引擎崩溃、异常、警告、BUG与提示总结及解决方法
  • 原文地址:https://www.cnblogs.com/xiaoyezi/p/8953980.html
Copyright © 2011-2022 走看看