ajax提交多个form表单

首先对某一表单进行Json对象序列化: 

 

引用:http://my249645546.iteye.com/blog/1617872

 

[javascript]  view plain  copy
 
  1. (function($){  
  2.         $.fn.serializeJson=function(){  
  3.             var serializeObj={};  
  4.             var array=this.serializeArray();  
  5.             var str=this.serialize();  
  6.             $(array).each(function(){  
  7.                 if(serializeObj[this.name]){  
  8.                     if($.isArray(serializeObj[this.name])){  
  9.                         serializeObj[this.name].push(this.value);  
  10.                     }else{  
  11.                         serializeObj[this.name]=[serializeObj[this.name],this.value];  
  12.                     }  
  13.                 }else{  
  14.                     serializeObj[this.name]=this.value;   
  15.                 }  
  16.             });  
  17.             return serializeObj;  
  18.         };  
  19.     })(jQuery);  


var proRuestl_1 = $("#proResult1").serializeJson();//数据序列化

var proRuestl_2= $("#proResult2").serializeJson();//数据序列化

var proRuestl_3= $("#proResult3").serializeJson();//数据序列化

 

然后对数据的合拼

 

[javascript]  view plain  copy
 
  1. $.extend(param, proRuestl_1,proRuestl_2,proRuestl_3);  


最后用ajax提交

 

[javascript]  view plain  copy
 
  1. $.ajax({  
  2.     type: "POST",  
  3.     async: false,  
  4.     url: 'XXXX',  
  5.     data: param,  
  6.     dataType: "json",  
  7.     success  :  })  


这样不单可以提交多个表单的参数,还可以防止乱码的出现!



===========================最新分割线===========================================

样例

var obj = {
       demandOrderId: "",
        applyUser: "",
        assetsName: "",
        realPrice:"",
        demandCount: "",
        applyCount: "",
        notApplyCount: "",
        allocationCount: "",
        createBy: "",
        createDate: "",
        updateBy: "",
        updateDate: "",
        createByCode: "",
        updateByCode: "",
        projectCode: "",
        specificationParameter: "",
        functions: "",
        optionalAccessories: "",
        acceptanceCriteria: "",
        standardComputer: "",
        referenceUnitPrice: "",
        referencePrice: "",
        inquiryUnitPrice: "",
        inquiryPrice: "",
        requirementsDate: "",
        costCenter: "",
        useDescription: "",
        units: "",
        applyUserCode: "",
        applyDepartment: "",
        applyDepartmentCode: "",
        assetType: "",
        referencePriceLocal: "",
        currencyCode: "",
        exchangeRate: "",
        inquiryPriceLocal: "",
        reducedBudgetLocal: "",
        notReducedBudgetLocal: "",
        budgetYear: "",
        budgetAssetsName:"",
        avaliableSumMoneyOld:""
   };
   var demandOrderWrapper = {};
   //添加表头
   objHeader = $("#demandOrderFormHeader").serializeObject();

   objFooter = $("#demandOrderFormFooter").serializeObject();
   //获得订单总金额
   objHeader.applyBudgetMoney = $("#sumTxtReferencePrice").val()==""?"0":$("#sumTxtReferencePrice").val();
   //获得申请部门名称
   //objHeader.applyDepartment = $("#txtApplyDepartment").find("option:selected").text();
   //获得公司名称
   //objHeader.companyName = $("#txtCompanyCode").find("option:selected").text();

   objHeader.building = $("input[name='building']:checked").val();
   //修改立项书的项目类型
   var strpt="";
   $("input:checkbox[name=projectType]:checked").each(function(){
      strpt += $(this).val()+"-*-*-";
   });
   strpt += $("#txtProjectType").val();
   objFooter.projectType = strpt;


   var objDemandOrder = $.extend({}, objHeader,objFooter);
   objDemandOrder.draft = strDraft;
   objDemandOrder.idea = idea;
   objDemandOrder.isMail = isMail;
   objDemandOrder.isPhoneMessage = isPhoneMessage;
   demandOrderWrapper.demandOrder = objDemandOrder;
   //公司名称
   objDemandOrder.companyName = $("#txtCompanyCode").find("option:selected").text();
   ///获得表单明细信息 封装Json对象
   var objArr = constructObjectFromTable(obj, $("#table_detail .bodyTr"));

   demandOrderWrapper.demandOrderDetails = objArr;
   //console.log(demandOrderWrapper);
    $.ajax({
           type: "POST",
           dataType: "json",
           async: false,
           contentType: "application/json; charset=utf-8",
           url: "${dynamicURL}/demand/api/saveDemand",
           data: JSON.stringify(demandOrderWrapper),
           success: function(data) {
               if (data.errorMessages.length > 0) {
                   var str = data.errorMessages;
                   alert(str);
            var reg = new RegExp("^.*保存成功.*$");
            if (reg.test(str)) {
               dg.curWin.location = dg.curWin.location;
            }
                   return;
               }
               alert("添加成功!");
               //关闭窗口
               dg.curWin.refresh();
               return;
           }
       });
}

function constructObjectFromTable(object, $object) {
   var javaObjArray = [];

   $object.each(function(i) {
        var javaObj = {};

        for (var p in object) {
           var $val = $(this).find('input[name="'+p+'"]');
           if ($val.length === 0) {
              javaObj[p] = $(this).find('select[name="'+p+'"]').val();
           } else {
              javaObj[p] = $val.val();
           }
        }

        javaObjArray.push(javaObj);
   });

   return javaObjArray;
}

后台controller和实体类

/**
 * 保存 新增
 *
 * @param demandOrderWrapper
 * @return
 */
@RequestMapping("/api/saveDemand")
@ResponseBody
public ExecuteResult saveDemand(@RequestBody DemandOrderWrapper demandOrderWrapper) {
    ExecuteResult executeResult = new ExecuteResult();
    //表头信息
    DemandOrder demandOrder = demandOrderWrapper.getDemandOrder();
    //明细信息
    List demandOrderDetails = demandOrderWrapper.getDemandOrderDetails();
   }
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class DemandOrderWrapper {
   private DemandOrder demandOrder;
   private List demandOrderDetails;
}


======================================================================

你可能感兴趣的:(js,java基础)