前端中不同页面之间传递参数的几种方式

1. 通过a标签传递参数,接收页面使用window.location.search获取页面

//01.html
<a href = '02.html?name=Auyuer'>click me to jump</a>



//02.html
function param(){
        var url=window.location.search;
        var params = url.substring(url.indexOf("?")+1);
        var par = params.split("=");
        var str = par[0]+':'+par[1];
        return str;
}

这里说一下Location对象属性都有哪些:

  • location.hash             可设置或返回从#开始的部分    
     例如 http://example.com:1234/test.htm#part2    得到的就是#part2
  • location.host                可设置或返回当前url的主机名称和端口号 (example.com:1234)
  • location.hostname       可设置或返回当前Url的主机名(example.com)
  • location.href           可设置或返回当前整个url(http://example.com:1234/test.htm#part2)
  • location.pathname      可设置或返回当前Url的路径部分(/text.html)
  • location.port                可设置或返回当前Url的端口部分(1234)
  • location.protocol          可设置或返回当前url的协议(http:)
  • location.search            可设置或返回当前 URL 的查询部分(?开始)

2. 通过手动给url拼接字符,利用window.open打开新窗口

   

<button id="btn">click me to jump</button>
<script>
    var btn = document.getElementById('btn');
    btn.onclick = function(){
        var url = '01 end.html?username=Auyuer';
        window.open(url, '_self')
    }
</script>
//window.open(URL,name,features,replace)

具体参数如下表所示:

在这里区别一下window.open()   和 Document.open()的区别:

<button onclick="createNewDoc()">点击写入新文档</button>


function createNewDoc()
    {
        var new_doc = document.open("text/html","replace");
        var txt = "<html><body>这是新的文档</body></html>";
        new_doc.write(txt);
        new_doc.close();
    }

//新文档用 document.write() 方法或 document.writeln() 方法写入内容,写入内容后,必须用 document.close() 方法关闭文档,并迫使其内容显示出来。

可自行运行下代码感受区别

window对象下有document对象

3. form表单提交数据

//01.html
<form action="01 end.html" method="get">
    <label for = 'username'>username:
        <input type="text" name="username" id = username/>
    </label>
    <input type="submit">
</form>

//02.html
param();
    function param(){
        var params = window.location.search;
        params = params.substring(params.indexOf('?')+1);
        params = params.split("=");
        console.log(params[0] + ':'+decodeURI(params[1]));
    }

这里使用decodeURI做一个转码

原文地址:https://www.cnblogs.com/Auyuer/p/8620690.html