window.location.search 为空?
1,什么是window.location?示例
URL:http://b.a.com:88/index.php?name=kang&when=2016#first
属性 含义 值
protocol: 协议 “http:”
hostname: 服务器的名字 “b.a.com”
port: 端口 “88”
pathname: URL中主机名后的部分 “/index.php”
search: "?“后的部分,又称为查询字符串 “?name=kang&when=2016”
hash: 返回”#"之后的内容 “#first”
host: 等于hostname + port “b.a.com:88”
href: 当前页面的完整URL “http://www.a.com:88/index.php?name=kang&when=2016#first”
window.location和document.location互相等价的,可以交换使用
location的8个属性都是可读写的,但是只有href与hash的写才有意义。例如改变location.href会重新定位到一个URL,而修改location.hash会跳到当前页面中的anchor(或者
注意
URL:http://b.a.com:88/index.php?name=kang&how=#when=2016#first
search:"?name=kang&how=" 第一个"?“之后
hash:”#when=2016#first" 第一个"#"之后的内容
2,为什么 window.location.search 为空?
答:注意上面的search和hash的区别,如果URL中“?”之前有一个“#”比如:“http://localhost:63342/index.html#/version?type=35&id=5”那么使用window.location.search得到的就是空(“”)。因为“?type=35&id=5”串字符是属于“#/version?type=35&id=5”这个串字符的,也就是说查询字符串search只能在取到“?”后面和“#”之前的内容,如果“#”之前没有“?”search取值为空。
3,应用
/**
* 解析URL传参
* @param {Object} key
*/
function getQueryString(key)
{
var after = window.location.search;
if(after.indexOf('?') === -1) return null; //如果url中没有传参直接返回空
//key存在先通过search取值如果取不到就通过hash来取
after = after.substr(1) || window.location.hash.split("?")[1];
if(after)
{
var reg = new RegExp("(^|&)"+ key +"=([^&]*)(&|$)");
var r = after.match(reg);
if(r != null)
{
return decodeURIComponent(r[2]);
}
else
{
return null;
}
}
}
引用 https://www.cnblogs.com/codebook/p/5918079.html
方法一:采用正则表达式获取地址栏参数:( 强烈推荐,既实用又方便!)
function GetQueryString(name)
{
var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if(r!=null)return unescape(r[2]); return null;
}
// 调用方法
alert(GetQueryString("参数名1"));
/**
* 获取url字符串参数
* 注意:此方法为vue hash模式特定方法,不适用其他渠道,是解决兼容微信分享链接中取参错误的问题?from=singlemessage&isappinstalled=0
*/
getQueryStr (urls = "") {
let url = urls || (window.location.href.split("#")[1] || window.location.href);
url = decodeURIComponent(url);
let result = {};
let arr = url.split("?");
let params = arr[1] && arr[1].split("&");
if (!params) return result;
for (let i = 0; i < params.length; i++) {
let item = params[i].split("=");
item[0] = decodeURIComponent(item[0]);
item[1] = decodeURIComponent(item[1]);
result[item[0]] = item[1];
}
return result;
},
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」