8.2 location对象
window.location与document.location都可以访问,是指向的同一对象。下面是location的属性的示例:
// 以下都以此url为例:https://www.baidu.com:80/index.html?rn=24&pn=1#home
// 返回url地址中#部分的字符
alert(location.hash); // home
// 返回服务器名称和端口号
alert(location.host); // www.baidu.com:80
// 返回服务器名称,不带端口号
alert(location.hostname); // www.baidu.com
// 返回当前加载页面的完整url,同toString()方法
alert(location.href); // https://www.baidu.com
// 返回url中的目录和文件名
alert(location.pathname); // index.html
// 返回url中的端口号
alert(location.port); // 80
// 返回页面使用的协议 http,https,ftp
alert(location.protocol); // https
// 返回URL的查询字符串,以?开头
alert(location.search); // ?rn=24&pn=1
8.2.1 查询字符串参数
search属性可以拿到所有查询字符串,不过是整个字符串,可以通过以下的函数来返回一个字典对象。
// 返回查询字符串
function getQueryStringArgs(){
var qs = (location.search.length > 0 ? location.search.substring(1) : "");
var args = {};
var items = qs.length ? qs.split("&") : [];
var item = null;
var name = null;
var value = null;
for (var i = 0;i < items.length;i++){
item = items[i].split("=");
name = decodeURIComponent(item[0]);
value = decodeURIComponent(item[1]);
if (name.length){
args[name] = value;
}
}
return args;
}
8.2.2 位置操作
// 以下三种方式都可以打开新的url
location.assign(url);
window.location = url;
window.location.href = url;
// 以下面方式修改location属性的话,相应的url也会改变
location.pathname = newValue;
通过上述的方式改变url会在历史记录里生成新的记录,可以使用后退按钮回到前一个页面,如果使用location.replace()方法则没有记录,会在1秒后重新定位到新的url。
window.location.replace(url);
// 重新加载,以最有效的方式加载(即没有更改的情况下,可能从缓存中加载)
window.location.reload();
// 重新加载,不管缓存中有不有,都从服务器中加载
window.location.reload(true);