js how to submit the ajax object and its associated object to the background through the object, replacing the form submission

Submitted usage scenarios

The backend uses the springmvc framework of java, so when you want to submit objects in the background, especially when the objects are complex, the objects in the background are associated with other objects, and there are other arrays or list objects associated with them, generally we use from The form is submitted to the backend.

Then if we need a better experience and front-end interaction, we need to use ajax technology when submitting, and then for data, we use data: $("#progressOrderForm").serialize() to achieve our purpose .

 $.ajax({
         type: 'POST',
         url: $("#rootPath").val() + "/buyer/process/order/fast/orderSave.htm",
         data: $("#progressOrderForm").serialize(),
         dataType: "json",
         success: function(data) {
             layer.close(indexLoad);
             alert(data.msg);
             if (!data.ok) {

                 $("#progressOrderForm").remove();
             } else {

                 //判断是 去订单列表还是 在当前页面! ,当前页面需要刷新
                 location.href = $("#rootPath").val() + "/retailIndex.htm";
             }
         },
         error: function(data) {
             layer.close(indexLoad);
             alert(data.msg);
         }
     });

Build a hidden from form, if there is no form form

But we need to have a form form. If we don't have a form, but want to use ajax to send the object to the background, how to write it through js? Of course, we can be a bit tedious, create a new form directly, and then put a lot of input in the form to submit it, for example:

function ajaxSubmit() {
     var indexLoad = layer.load(1, {
         shade: [0.5, '#fff'] //0.1透明度的白色背景
     });

     $.ajax({
         type: 'POST',
         url: $("#rootPath").val() + "/buyer/process/order/fast/orderSave.htm",
         data: $("#progressOrderForm").serialize(),
         dataType: "json",
         success: function(data) {
             layer.close(indexLoad);
             alert(data.msg);
             if (!data.ok) {

                 $("#progressOrderForm").remove();
             } else {

                 //判断是 去订单列表还是 在当前页面! ,当前页面需要刷新
                 location.href = $("#rootPath").val() + "/retailIndex.htm";
             }
         },
         error: function(data) {
             layer.close(indexLoad);
             alert(data.msg);
         }
     });
 }

 /**
  * 构造订单明细和检验, 以便提交
  order_status 订单状态 : 保存或者是 提交
  */
 function createOrdersAndDetailListAndCheck(order_status) {
     // 校验 其他的,比如是否登录,比如 是否 填好地址等


     createFormToSubmit();

     //先构建订单主表的数据
     //判断是否选择了地址
     var address_id = $("#address_id").val();
     if (address_id == "") {
         notPassCheckTodo('请选择送货地址!');
         return false;
     }
     var order_id = $("#order_id").val(); //订单id,如果是修改的话
     var user_id = $("#user_id").val(); //买家id
     var buyer_msg = $("#buyer_msg").text(); //买家留言


     var order = new Map();
     if (order_id) {
         order.set('id', order_id);
     }

     order.set('user.id', user_id);
     order.set('orderStatus', order_status);
     order.set('addr.id', address_id); //订单地址id
     order.set('buyerMsg', buyer_msg);

     order.set("isTax", isTax);
     order.set("weightWay", weightWay);
     order.set('deliveryMode', deliveryMode);
     creatFormOrderHidden(order); //构建表单数据


     $(".form_list_ul").each(function(i) {
         var mat = $(this).find('[name="mat"]').val();
         var detailId = $(this).find("input[name='peDetails_id']").val();
         var peDetails_inciseWay = $(this).find('[name="peDetails_inciseWay"]').val();
         var num = $(this).find('[name="Number_id"]').val();
         var peDetails_spec_type = parseInt($(this).find('[name="type1"]').val());
         var thickness = $(this).find("input[name='peDetails_thickness0']").val();
         var width = $(this).find("input[name='peDetails_width0']").val();
         var length = $(this).find("input[name='peDetails_length0']").val();
         var consultWeight = $(this).find("input[name='Reference']").val();
         var modelNo = $(this).find("input[name='modelNo']").val();
         var unitPrice = $(this).find("input[name='unitPrice']").val();
         var totalPrice = $(this).find("input[name='totalPrice']").val();
         if (totalPrice == "" || unitPrice == "") {
             return true; //跳过本次循环,进行入下一次
         }



         var df_w0 = $(this).find("input[name='df_w0']").val(); //宽下偏差
         var df_w1 = $(this).find("input[name='df_w1']").val(); //宽上偏差
         var df_h0 = $(this).find("input[name='df_h0']").val(); // 长下偏差
         var df_h1 = $(this).find("input[name='df_h1']").val(); //长上偏差

         var msgDf = checkTolerances(df_w0, df_w1, df_h0, df_h1);
         if (msgDf != "ok") {

             notPassCheckTodo(msgDf);
             return false;
         }

         if (mat != "" && thickness != "" && width != "" && length != "" && num != "") {

             /*var dataItem = {
             	"id": detailId ,//明细的id
             	"inciseWay": peDetails_inciseWay, //切割方式
             	"texture": mat, //材质
             	"count": num, //件数
             	"specType": peDetails_spec_type, //规格类型
             	"thickness": thickness, //厚度
             	"width": width, //宽度
             	"length": length, //高度
             	"totalWeight": consultWeight, //参考重量
             	"modelNo": modelNo ,//模号,
             	"unitPrice":unitPrice,//单价
             	"totalPrice":totalPrice ,//总价,
             	"widthDownTolerances":df_w0 ,//宽下偏差
             	"widthUpTolerances":df_w1,//宽上偏差
             	"lengthDownTolerances":df_h0,//高下偏差
             	"lengthUpTolerances":df_h1,//高的上偏差
             	"isTax":isTax,//是否含税
             	"weightWay":weightWay,//计重方式
             	 "deliveryMode":deliveryMode//提货方式
             };*/

             var dataItemMap = new Map();
             dataItemMap.set('id', detailId);
             dataItemMap.set('inciseWay', peDetails_inciseWay);
             dataItemMap.set('texture', mat);
             dataItemMap.set('count', num);
             dataItemMap.set('specType', peDetails_spec_type);
             dataItemMap.set('thickness', thickness);
             dataItemMap.set('width', width);
             dataItemMap.set('length', length);
             dataItemMap.set('totalWeight', consultWeight);
             dataItemMap.set('modelNo', modelNo);
             dataItemMap.set('unitPrice', unitPrice);
             dataItemMap.set('widthDownTolerances', df_w0);
             dataItemMap.set('widthUpTolerances', df_w1);
             dataItemMap.set('lengthDownTolerances', df_h0);
             dataItemMap.set('lengthUpTolerances', df_h1);
             dataItemMap.set('isTax', isTax);
             dataItemMap.set('weightWay', weightWay);
             dataItemMap.set('deliveryMode', deliveryMode);


             creatFormOrderItemHidden(dataItemMap, i); //构建明细表单数据

         } else {
             i = i + 1;
             var msg = "第" + i + "条数据不完整,无法提交";
             notPassCheckTodo(msg);
             return false;
         }

     });

 }

 //创建一个隐藏的form 表单方便提交 
 function createFormToSubmit() {
     var formStr = ' <form  method="post" accept-charset="utf-8"  id="progressOrderForm" style="display:none;" > ';
     formStr += '  </form> ';

     $("body").append(formStr);

 }

 // 构建 订单主表数据
 function creatFormOrderHidden(orderMap) {
     orderMap.forEach(function(value, key, orderMap) {
         createHiddenField(key, value);
     });
 }

 //构建订单明细表数据
 function creatFormOrderItemHidden(orderMap, i) {
     var itemsStr = "items[" + i + "].";
     orderMap.forEach(function(value, key, orderMap) {
         createHiddenField(itemsStr + key, value);
     });
 }

 /**
  * 一个Hidden
  * @param name
  * @param value
  * @returns {String}
  */
 function createHiddenField(name, value) {
     var input = "<input type='hidden' name='" + name + "' value='" + value + "'>\n";
     $("#progressOrderForm").append(input);

 }

Easy way to use js

By customizing a form, the effect can be achieved, but it does not feel very cumbersome, and the execution efficiency is relatively low, and the form may also have the same name or something. Reuse is also poor. So I want to improve it through the object method of js to achieve the desired effect.

Examples of objects in the background:

@RequestMapping("/mytest/testjson")
	@ResponseBody
	public String testallipay(Role role, HttpServletRequest req, HttpServletResponse response) {

		// System.out.println(user.getId().toString() + ">>>>>" + user.getName());
		// System.out.println("##############>>>>>" + user.getMemberNumber().getId());
		System.out.println(role.getId() + ">>>>>" + role.getRoleName());
		System.out.println(role.getMenuroles().get(0).getId());
		System.out.println(role.getMenuroles().get(1).getId());
		
		return "aa";

	}

这样我们需要 前端传入一个 role 对象, 可是对象role 里面有 一个 
 /**
     * 菜单角色
     */
    private List<Menurole> menuroles;

   private User user;//用户对象

如果需要前端 也将 menuroles 传入 role里面 怎么 写呢?

js object writing 2 kinds of the same effect

var obj = new Object();
			 //  obj.id='22';  和下面的方式是一样的
			 obj["id"]='22';

可以看到 对象 obj 定义一个 属性 id ,写法 可以有两种方式。
这样就方便我们 自定义对象属性 给后端了。

Examples are as follows:

                      var obj = new Object();
			  obj["id"]='22';
			  obj.roleName='oumin';
			  obj["menuroles[0].id"]='88';
			  obj["menuroles[1].id"]='99';
                            obj["user.id"]='991'; //传递 单个对象的写法
                        
			   
			

			   console.log('>>'+JSON.stringify(obj));//输出json 字符串
结果: {"id":"22","roleName":"oumin","menuroles[0].id":"88","menuroles[1].id":"99","user.id":"991"}

                            //ajax 想后台提交 role对象
                            $.ajax({
					type: 'POST',
					dataType: "json",
					url: "/mytest/testjson",
					data:obj,
					
					success: function(data) {
						console.log(data);
					},
					error: function(data) {
						
						console.log(data);
					}
				});

这样子就达到我们的效果了。
是不是 比通过 form 表单的方式 效率高多了!
而且在 动态获取对象的数据的时候, 可以灵活进行获取了。



Summarize

In fact, the property writing of the js object is the same as the name of the name submitted to the backend of the form form. What is the corresponding name of the form form, then what is the name of our obj attribute, and the assignment can be done. This is more flexible and does not require a form at all. In fact, everyone has not known how to write the properties of objects. I've always been ignorant of how to write it, and I don't know how to write the front-end to the back-end so that it can be parsed.

By the way, the way to build a json string from a js object

 var obj3 = new Object();
				
				 obj3["id"]='22';
				   obj3.name='oumin';
				 
				  var memberNumber=new Object();
				   memberNumber.id='88';
				   obj3["memberNumber"]=memberNumber; 
				   console.log('3>>>>'+JSON.stringify(obj3));// 这样就可以获取到 正常的 json字符串了
//   {"id":"22","name":"oumin","memberNumber":{"id":"88"}}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325303779&siteId=291194637