JS 跳转到新页面并用post传参

今天在开发的过程中有一个需求,要求:打开一个新的页面同时传参

这个不难实现 <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&param2=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);
}    

 

 

【参考】

  1. https://www.runoob.com/jsref/met-win-open.html  
  2. https://blog.csdn.net/u013303551/article/details/52909871

 

posted @ 2019-04-25 19:50  坚持的力量々  阅读(10929)  评论(0编辑  收藏  举报