一、location对象
http://localhost:8881/javascript/BOM/window.html?name=bob&age=123console.log('获取hash:', window.location.hash);// 获取服务器名称和端口号host: localhost:8881console.log('获取服务器名称和端口号host:', window.location.host);// 获取服务器名称和端口号host: localhost:8881console.log('获取不带端口号的服务器名称hostname:', window.location.hostname);// 获取不带端口号的服务器名称hostname: localhostconsole.log('获取整个url href:', window.location.href);// 获取整个url href: http://localhost:8881/javascript/BOM/window.html?name=bob&age=123console.log('返回URL中的目录和(或)文件名pathname', window.location.pathname);// 返回URL中的目录和(或)文件名pathname /javascript/BOM/window.htmlconsole.log('返回url的端口号', window.location.port);// 返回url的端口号 8881console.log('返回url的协议 protocol', window.location.protocol);// 返回url的协议 protocol http:console.log('返回URL的查询字符串 这个字符串以问号开头 search', window.location.search);// 返回URL的查询字符串 这个字符串以问号开头 search ?name=bob&age=123
二、查询字符串参数
function getQueryStringArgs() { //取得查询字符串并去掉开头的问号 var qs = (location.search.length > 0 ? location.search.substring(1) : ""), //保存数据的对象 args = {}, //取得每一项 items = qs.length ? qs.split("&") : [], item = null, name = null, value = null, //在for循环中使用 i = 0, len = items.length; //逐个将每一项添加到args对象中 for (i = 0; i < len; i++) { item = items[i].split("="); name = decodeURIComponent(item[0]); value = decodeURIComponent(item[1]); if (name.length) { args[name] = value; } } return args;}console.log(getQueryStringArgs()); // {name: "bob", age: "123"}
三、位置修改
//假设初始URL为http://www.wrox.com/WileyCDA///将URL修改为"http://www.wrox.com/WileyCDA/#section1"location.hash = "#section1";//将URL修改为"http://www.wrox.com/WileyCDA/?q=javascript"location.search = "?q=javascript";//将URL修改为"http://www.yahoo.com/WileyCDA/"location.hostname = "www.yahoo.com";//将URL修改为"http://www.yahoo.com/mydir/"location.pathname = "mydir";//将URL修改为"http://www.yahoo.com:8080/WileyCDA/"location.port = 8080;
四、加载
location.assign("http://www.wrox.com");location.href = "http://www.wrox.com";location.replace("http://www.wrox.com/");location.reload(); //重新加载(有可能从缓存中加载)location.reload(true); //重新加载(从服务器重新加载)