通常我們用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" }