虽然通过ocation 对象的可以得到大多数信息,但其中访问 URL 包含的查询字符 串的属性并不方便。尽管 location.search 返回从问号到 URL 末尾的所有内容,但却没有办法逐个 访问其中的每个查询字符串参数。为此,可以像下面这样创建一个函数,用以解析查询字符串,然后返 回包含所有参数的一个对象:
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
}
举个例子:
http://www.renjie.net.cn/index.html?name=%22jason%22&sex=1
在上面这个地址下用 getQueryStringArgs() 就可以得到如下对象:{name: ""jason"", sex: "1"}