location对象用来处理URL的相关信息
1、获取查询字符串
// 获取查询字符串对象 var getQueryStringArgs = function () { var qs = (location.search.length > 0 ? location.search.slice(1) : ""), args = {}, // 保存要返回的数据对象 items = (qs.length > 0 ? qs.split("&") : []), // &符split后的数组,数据项 item = [], // =号split后的数组,每个数据项的json表达 name = "", value = "", // len = items.length, i; for (i = 0; i < len; i += 1) { item = items[i].split("="); // 查询字符串应该是被编码过的,所以解码 name = decodeURIComponent(item[0]); value = decodeURIComponent(item[1]); if (name.length) { args[name] = value; } } return args; };
2、location 与 http 请求
// 一个含有search 和 hash的url,查询字符串要在hash片段的前面 var url = "http://www.so.com/?q=javascript#section1"; // 切换到新的地址 location.href = "http://www.so.com/"; // 添加查询字符串重新请求 location.search = "?q=javascript"; // 到目标目录文件夹发起新的请求 location.pathname = "js"; // 向url添加hash字符串,不会产生新的http请求 location.hash = "#section1"; // 刷新页面 location.reload(); // 强制刷新页面 location.reload(true); // 补充history:返回的特定的历史记录,发起新的http请求 history.go(-1);