post方式打开页面
通常我们用window.open或者点击a标签链接都是以get方式打开了一个新页面,弊端就是参数全部拼接在url上,并且参数显示在地址栏中,如果我们不想让一些敏感信息显示在地址栏中,或者就单纯的在传输参数过多时,不想让url过长,我们就可以通过以下方式实现,并且get方式传输数据是有长度限制的,可能有时不能满足我们的需求
实现原理:模拟form表单提交
js代码:
//调用
var url ="hotelDetails?attendId=" + attendId + "&hotelUid=" + hotelUid;
var conditions = {};
conditions.checkinStart = $('.Date_lr').attr('data-start'); //入住日期
conditions.checkinEnd = $('.Date_lr').attr('data-end'); //离店日期
conditions.roomNumber = $('#rnum').val(); //房间数量
conditions.personNumber = $('#pnum').val(); //人数
postOpenWindow(url, JSON.stringify(conditions), "_self");
function postOpenWindow(url, data, target){ var tempForm = document.createElement("form"); tempForm.id = "tempForm"; tempForm.method = "post"; tempForm.action = url; tempForm.target = target; //打开方式 tempForm.style.display = "none"; var hideInput = document.createElement("input"); hideInput.type = "hidden"; hideInput.name = "content" hideInput.value = data; tempForm.appendChild(hideInput); document.body.appendChild(tempForm); tempForm.submit(); document.body.removeChild(tempForm); }
我这里传输了一个json串,这个串可以任意大小,后台直接从request请求中获取参数(request.getParameter("content"))并解析json就拿到json对象了
后台代码:
@RequestMapping("/hotelDetails")
public String hotelDetails(HttpServletRequest request, Long attendId, String hotelUid) { String content = request.getParameter("content"); ObjectMapper mapper = new ObjectMapper(); Map<String, Object> conditions = mapper.readValue(content, Map.class); return "index" }