1、在WEB开发中,网页之间互相传递通过url来传递参数是特别常见的,那么我们如何的从url中获取传递过来的参数呢,我们下面就来总结一下使用JavaScript获取url网址参数的一些方法以及常用的api。
2、首先我们提供一个网址比如:http://tieba.baidu.com/f?kw=java&fr=ala0&tpl=5
一、我们首先说一下获取网址各部分信息的api:
1)window.location.href (设置或获取整个 URL 为字符串)
var url = window.location.href;
console.log(url);
返回:http://tieba.baidu.com/f?kw=java&fr=ala0&tpl=5
2)window.location.protocol (设置或获取 URL 的协议部分)
var url= window.location.protocol;
console.log(url);
返回:http:
3)window.location.host (设置或获取 URL 的主机部分)
var url= window.location.host;
console.log(url);
返回:tieba.baidu.com
4)window.location.port (设置或获取与 URL 关联的端口号码)
var url= window.location.port;
console.log(url);
返回:空字符(如果采用默认的80端口(update:即使添加了:80),那么返回值并不是默认的80而是空字符)
5)window.location.pathname (设置或获取与 URL 的路径部分(就是文件地址))
var url= window.location.pathname;
console.log(url);
返回:/f
6)window.location.search (设置或获取 href 属性中跟在问号后面的部分)
var test = window.location.search;
console.log(url);
返回:?kw=java&fr=ala0&tpl=5
PS:获得查询(参数)部分,除了给动态语言赋值以外,我们同样可以给静态页面,并使用javascript来获得相信应的参数值。
7)window.location.hash (设置或获取 href 属性中在井号“#”后面的分段)
var url= window.location.hash;
console.log(url);
返回:空字符(因为url中没有)
二、js获取url中的参数值的方法:
1、使用正则表达式来获取:
关于下面正则表达式详解的文章:https://blog.csdn.net/weixin_44296929/article/details/101207166
function getQueryString(name) {
var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
var r = window.location.search.substr(1).match(reg);
if (r != null) {
return unescape(r[2]);
}
return null;
}
2、使用split方法拆分:
首先使用location.search获取url中的参数,然后通过split方法来进行拆分
function GetRequest() {
var url = location.search; //获取url中"?"符后的字串
var theRequest = new Object();
if (url.indexOf("?") != -1) { //不是-1说明?后面有参数
var str = url.substr(1); //截取?后面的部分(即参数部分)
strs = str.split("&"); //将参数部分使用split进行拆分
for(var i = 0; i < strs.length; i ++) { //遍历将参数和参数值赋值给我们创建好的对象
theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
}
}
return theRequest;
}
var Request = new Object();
Request = GetRequest();<br>// var id=Request["id"];
// var 参数1,参数2,参数3,参数N;
// 参数1 = Request['参数1'];
// 参数2 = Request['参数2'];
// 参数3 = Request['参数3'];
// 参数N = Request['参数N'];
你要去做一个大人,不要回头,不要难过。
“他们都在看烟花,无人想起你。”