这里有很多好的解决方案,但我想我会发布自己的。这是我放在一起的一个快速小函数,它将解析来自 window.location.search 或提供的搜索字符串值格式的查询字符串;
它返回一个 id 值对的哈希值,因此您可以通过以下形式引用它:
var values = getQueryParams();
values['id']
values['blah']
这是代码:
/*
This function assumes that the query string provided will
contain a ? character before the query string itself.
It will not work if the ? is not present.
In addition, sites which don't use ? to delimit the start of the query string
(ie. Google) won't work properly with this script.
*/
function getQueryParams( val ) {
//Use the window.location.search if we don't have a val.
var query = val || window.location.search;
query = query.split('?')[1]
var pairs = query.split('&');
var retval = {};
var check = [];
for( var i = 0; i < pairs.length; i++ ) {
check = pairs[i].split('=');
retval[decodeURIComponent(check[0])] = decodeURIComponent(check[1]);
}
return retval;
}
要在不解析字符串的情况下从 URL 获取查询字符串的值,您可以执行以下操作:
window.location.search.substr(1)
如果要在 ? 之前的页面名称?你仍然需要做一些字符串解析:
var path = window.location.pathname.replace(/^.*\/(.*)$/,'$1');
var query = path + window.location.search;
//If your URL is http://www.myserver.com/some/long/path/big_long%20file.php?some=file&equals=me
//you will get: big_long%20file.php?some=file&equals=me
希望这可以帮助!干杯。