<script>
// 设置或获取整个 URL 为字符串
// 文件访问 file:///F:/phpStud/PHPTutorial/WWW/CasPHP/public/js/js_url.html
// 域名访问 http://casphp.com/js/js_url.html
console.log(window.location.href);
//设置或获取 URL 的协议部分
console.log(window.location.protocol); //http: file:
console.log(location.protocol); //http: 或者 file:
// 设置或获取 URL 的主机部分
console.log(window.location.host); //casphp.com
// 设置或获取与 URL 关联的端口号码
console.log(window.location.port); //80
// 设置或获取与 URL 的路径部分(就是文件地址)
// 文件访问 file:///F:/phpStud/PHPTutorial/WWW/CasPHP/public/js/js_url.html?a=123
// 返回值 /F:/phpStud/PHPTutorial/WWW/CasPHP/public/js/js_url.html
// 域名访问 http://casphp.com/js/js_url.html?a=123
// 返回值 /js/js_url.html
console.log(window.location.pathname);
// 设置或获取 href 属性中跟在问号后面的部分
// http://casphp.com/js/js_url.html?a=123
console.log(window.location.search); // ?a=123
// 中文自动转码 http://casphp.com/js/js_url.html?a=%E4%B8%AD%E5%9B%BD
console.log(window.location.search); // ?a=%E4%B8%AD%E5%9B%BD
//设置或获取 href 属性中在井号“#”后面的分段
// http://casphp.com/js/js_url.html#cc?a=123
console.log(window.location.hash); // #cc?a=123
console.log(window.location.search); // 返回为空
// 中文自动转码 http://casphp.com/js/js_url.html#dd?a=%E4%B8%AD%E5%9B%BD
console.log(window.location.hash); // #dd?a=%E4%B8%AD%E5%9B%BD
//js 获取路由参数
function getUrlParam(){
// 取得参数
var query_param=window.location.search;
// 截取? 后面的字符串,以& 连接符分割字符串
var new_query=query_param.substring(1).split('&');
// 定义存放对象
var query_obj={};
new_query.forEach(e=>{
// 分割后 后转为字符串,如果参数需要数值类型,调用时要处理一下
let list=e.split('=');
// 解码
let key=decodeURI(list[0]);
let val=decodeURI(list[1]);
// 去除空格
let new_key=key.replace(/(^\s*)|(\s*$)/g,'');
let new_val=val.replace(/(^\s*)|(\s*$)/g,'');
// 存入对象
query_obj[new_key]=new_val
});
return query_obj
}
// 调用示例
var url_query=getUrlParam();
// http://casphp.com/js/js_url.html?a=123
console.log(url_query.a);// 123
// http://casphp.com/js/js_url.html?a=%E4%B8%AD%E5%9B%BD
console.log(url_query.a);// 中国
console.log(url_query.b); // undefined
</script>