js获取地址栏参数

方法一:

getRequest(url) {
	const res = {}
	if (url.includes('?')) {
		const str = url.split('?')[1]
		const arr = str.split('&')
		arr.forEach(item => {
			const key = item.split('=')[0]
			const val = item.split('=')[1]
			res[key] = decodeURIComponent(val) // 解码
		})
	}
	return res
},
// url  :http://192.168.11.101:8082/#/pages/gate/qrc?channelId=12&id=3
console.log(this.getRequest(window.location.href))
// {
//  channerlId:'12',
//  id:'3'
// }

方法二:

// 创建一个URLSearchParams实例
const urlSearchParams = new URLSearchParams(window.location.search);
// 把键值对列表转换为一个对象
const params = Object.fromEntries(urlSearchParams.entries());
console.log(params)  //  { user: '阿飞', age: '16' }

window.location常用方法介绍

1,window.location.href
整个URl字符串(在浏览器中就是完整的地址栏)
本例返回值 http://192.168.11.101:8082/#/pages/gate/qrc?channelId=12&id=3

2,window.location.protocol
URL 的协议部分
本例返回值:http:

3,window.location.host
URL 的主机部分
本例返回值:192.168.11.101:8082

4,window.location.port
URL 的端口部分
如果采用默认的80端口(update:即使添加了:80),那么返回值并不是默认的80而是空字符
本例返回值:8082

5,window.location.pathname
URL 的路径部分(就是文件地址)
本例返回值:/

6,window.location.search
查询(参数)部分
除了给动态语言赋值以外,我们同样可以给静态页面,并使用javascript来获得相信应的参数值
本例返回值:?channelId=12&id=3

7,window.location.hash
锚点

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值