Location 对象
Location 对象包含有关当前 URL 的信息
Location 对象是 Window 对象的一个部分,可通过 window.location 属性来访问
Location的各种属性:
window.location.hash => 设置或返回从井号 (#) 开始的 URL(锚)
window.location.host => 设置或返回主机名和当前 URL 的端口号
window.location.hostname => 设置或返回当前 URL 的主机名
window.location.href => 设置或返回完整的 URL
window.location.pathname => 设置或返回当前 URL 的路径部分
window.location.port => 设置或返回当前 URL 的端口号
window.location.protocal => 设置或返回当前 URL 的协议
window.location.search => 设置或返回从问号 (?) 开始的 URL(查询部分)
方法一:
// 根据参数名获取url中的参数
function getQueryString(name) {
const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
const urlObj = window.location;
var r = urlObj.href.indexOf('#') > -1 ? urlObj.hash.split("?")[1].match(reg) : urlObj.search.substr(1).match(reg);
if (r != null) return unescape(r[2]); return null;
}
alert(getQueryString("参数名称"));
方法二:
// 根据参数名获取url中的参数
function GetQueryString(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
var r = window.location.search.substr(1).match(reg); //获取url中"?"符后的字符串并正则匹配
var context = "";
if (r != null)
context = r[2];
reg = null;
r = null;
return context == null || context == "" || context == "undefined" ? "" : context;
}
// 调用
var 参数1 = GetQueryString['参数1'];
var 参数2 = GetQueryString['参数2'];
var 参数3 = GetQueryString['参数3'];
方法三:
// 根据参数名获取url中的参数
function GetRequest() {
var url = location.search; //获取url中"?"符后的字串
var theRequest = new Object();
if (url.indexOf("?") != -1) {
var str = url.substr(1);
strs = str.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();
var 参数1,参数2,参数3,参数N;
参数1 = Request['参数1'];
参数2 = Request['参数2'];
参数3 = Request['参数3'];
参数N = Request['参数N'];