获取URL中的查询参数
// 定义函数获取URL查询参数并返回一个对象
function GetRequest() {
let url = location.href; // 获取完整的URL
let theRequest = {};
if (url.indexOf('?') != -1) {
let str = url.substr(url.indexOf('?') + 1); // 获取'?'后面的字符串
let strs = str.split('&'); // 将查询参数按'&'进行分割
for(let i = 0; i < strs.length; i++) {
// 将每个参数名和参数值存储到对象中
theRequest[strs[i].split('=')[0]] = unescape(strs[i].split('=')[1]);
}
}
return theRequest;
}
let request = GetRequest(); // 调用函数
console.log(request['i_code']); // 打印查询参数'i_code'的值
获取URL的各个组成部分
// 以下是一些示例,展示如何使用window.location获取URL的不同部分:
// 1. 获取完整的URL
var test = window.location.href;
alert(test); // http://i.jb51.net/EditPosts.aspx?opt=1
// 2. 获取URL的协议部分
var test = window.location.protocol;
alert(test); // http:
// 3. 获取URL的主机部分
var test = window.location.host;
alert(test); // i.jb51.net
// 4. 获取URL的端口号
var test = window.location.port;
alert(test); // 如果默认端口是80,则返回空字符串
// 5. 获取URL的路径部分
var test = window.location.pathname;
alert(test); // /EditPosts.aspx
// 6. 获取URL的查询参数部分
var test = window.location.search;
alert(test); // ?opt=1
// 7. 获取URL的锚点部分
var test = window.location.hash;
alert(test); // 如果URL中没有井号“#”后面的部分,则返回空字符串