前言
前端有数据需要请求后端,但并不是直接的表单控件里的内容,而且不能走Ajax方式,因为要直接在后端重定向到新的页面。因此通过js构建一个表单请求实现该功能。
一、方案
传到前端的数据是数组格式。
// 方案1
function payment() {
// 创建form
let form = document.createElement("form");
// 请求地址、方式
form.action = "payment";
form.method = "POST";
// 将form放到body中
document.body.appendChild(form);
// 创建表单元素
$("input[type='checkbox'][name='merchandise']:checked").each(function () {
let input = document.createElement("input");
input.type = "hidden";
input.name = "merchandiseIds";
input.value = $(this).val();
form.appendChild(input);
let input1 = document.createElement("input");
input1.type = "hidden";
input1.name = "quantity";
input1.value = $("#sum" + $(this).val()).val();
form.appendChild(input1);
});
// 提交表单
form.submit();
// 清除from
document.body.removeChild(form)
}
// 方案2
function payment() {
// 创建form
let form = document.createElement("form");
// 请求地址、方式
form.action = "payment";
form.method = "POST";
// 将form放到body中
document.body.appendChild(form);
// 创建表单元素
let arr = [];
let quantity = [];
$("input[type='checkbox'][name='merchandise']:checked").each(function () {
arr.push($(this).val())
quantity.push($("#sum" + $(this).val()).val());
});
let input = document.createElement("input");
input.type = "hidden";
input.name = "merchandiseIds";
input.value = arr;
form.appendChild(input);
let input1 = document.createElement("input");
input1.type = "hidden";
input1.name = "quantity";
input1.value = quantity;
form.appendChild(input1)
// 提交表单
form.submit();
// 清除from
document.body.removeChild(form)
}
实际上两个方案差不多,只不过有表单数量上的差异。
二、后端接收
直接用SubmittedOrder这个对象接收参数。
@RequestMapping(value = "payment", method = RequestMethod.POST)
public String payment(HttpServletRequest req, HttpServletResponse res, Model model, SubmittedOrder submittedOrder) {
return webService.payment(req, res, model, submittedOrder);
}
参考:http://events.jianshu.io/p/c2546d8fd478