
今天在開發的過程中有一個需求,要求:打開一個新的頁面同時傳參。
這個不難實現 <a> 標簽 就可以實現,但它卻是使用 get方式傳參,這種直接將參數拼接在 url 的方式(url + ? + 參數)是不安全的,數據直接暴露在地址欄,而且由於不同的瀏覽器對於地址欄的長度也有限制,導致參數也是有大小限制的。那么能不能使用 post方式傳參呢? 下面就來介紹各種打開新頁面以及傳參的方式。
1 超鏈接<a>標簽 (get傳參)
<a href="http://www.cnblogs.com/pan1042/" target="_blank">
2 window.open() (get傳參)
window.open(URL,name,specs,replace)
例: window.open(url + "? param1=value1¶m2=value2", "_blank")
3 form (post傳參)
function openPostWindow(url, data, name) { var tempForm = document.createElement("form"); tempForm.id = "tempForm1"; tempForm.method = "post"; tempForm.action = url; tempForm.target = name; // _blank - URL加載到一個新的窗口 var hideInput = document.createElement("input"); hideInput.type = "hidden"; hideInput.name = "content"; hideInput.value = data; tempForm.appendChild(hideInput); // 可以傳多個參數 /* var nextHideInput = document.createElement("input"); nextHideInput.type = "hidden"; nextHideInput.name = "content"; nextHideInput.value = data; tempForm.appendChild(nextHideInput); */ if(document.all){ // 兼容不同瀏覽器 tempForm.attachEvent("onsubmit",function(){}); //IE }else{ tempForm.addEventListener("submit",function(){},false); //firefox } document.body.appendChild(tempForm); if(document.all){ // 兼容不同瀏覽器 tempForm.fireEvent("onsubmit"); }else{ tempForm.dispatchEvent(new Event("submit")); } tempForm.submit(); document.body.removeChild(tempForm); }
【參考】
- https://www.runoob.com/jsref/met-win-open.html
- https://blog.csdn.net/u013303551/article/details/52909871
