是否有一种通过jQuery(或不使用)检索查询字符串值的无插件方法?
如果是,怎么办?如果没有,是否有插件可以这样做?
是否有一种通过jQuery(或不使用)检索查询字符串值的无插件方法?
如果是,怎么办?如果没有,是否有插件可以这样做?
当前回答
我宁愿使用split()而不是Regex执行此操作:
function getUrlParams() {
var result = {};
var params = (window.location.search.split('?')[1] || '').split('&');
for(var param in params) {
if (params.hasOwnProperty(param)) {
var paramParts = params[param].split('=');
result[paramParts[0]] = decodeURIComponent(paramParts[1] || "");
}
}
return result;
}
其他回答
下面是一种快速获取类似于PHP$_get数组的对象的方法:
function get_query(){
var url = location.search;
var qs = url.substring(url.indexOf('?') + 1).split('&');
for(var i = 0, result = {}; i < qs.length; i++){
qs[i] = qs[i].split('=');
result[qs[i][0]] = decodeURIComponent(qs[i][1]);
}
return result;
}
用法:
var $_GET = get_query();
对于查询字符串x=5&y&z=hello&x=6,这将返回对象:
{
x: "6",
y: undefined,
z: "hello"
}
Use:
$(document).ready(function () {
var urlParams = {};
(function () {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) {
return decodeURIComponent(s.replace(pl, " "));
},
query = window.location.search.substring(1);
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
})();
if (urlParams["q1"] === 1) {
return 1;
}
请检查并让我知道您的意见。另请参阅How to get querystring value using jQuery。
这里有一个很好的小url实用程序,带有一些很酷的糖霜:
http://www.example.com/path/index.html?silly=willy#chucky=cheese
url(); // http://www.example.com/path/index.html?silly=willy#chucky=cheese
url('domain'); // example.com
url('1'); // path
url('-1'); // index.html
url('?'); // silly=willy
url('?silly'); // willy
url('?poo'); // (an empty string)
url('#'); // chucky=cheese
url('#chucky'); // cheese
url('#poo'); // (an empty string)
查看更多示例并在此处下载:https://github.com/websanova/js-url#url
function GET() {
var data = [];
for(x = 0; x < arguments.length; ++x)
data.push(location.href.match(new RegExp("/\?".concat(arguments[x],"=","([^\n&]*)")))[1])
return data;
}
example:
data = GET("id","name","foo");
query string : ?id=3&name=jet&foo=b
returns:
data[0] // 3
data[1] // jet
data[2] // b
or
alert(GET("id")[0]) // return 3
试试看:
String.prototype.getValueByKey = function(k){
var p = new RegExp('\\b'+k+'\\b','gi');
return this.search(p) != -1 ? decodeURIComponent(this.substr(this.search(p)+k.length+1).substr(0,this.substr(this.search(p)+k.length+1).search(/(&|;|$)/))) : "";
};
然后这样称呼:
if(location.search != "") location.search.getValueByKey("id");
您还可以将此用于cookie:
if(navigator.cookieEnabled) document.cookie.getValueByKey("username");
这只适用于key=value[&|;|$]。。。将无法处理对象/数组。
如果您不想使用String.prototype。。。将其移动到函数并将字符串作为参数传递