是否有一种通过jQuery(或不使用)检索查询字符串值的无插件方法?
如果是,怎么办?如果没有,是否有插件可以这样做?
是否有一种通过jQuery(或不使用)检索查询字符串值的无插件方法?
如果是,怎么办?如果没有,是否有插件可以这样做?
当前回答
我喜欢这个(摘自jqueryhowto.blogspot.co.uk):
// get an array with all querystring values
// example: var valor = getUrlVars()["valor"];
function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
对我来说很棒。
其他回答
我使用这里列出的技术开发了一个小型库,以创建一个易于使用的解决方案;可以在这里找到:
https://github.com/Nijikokun/query-js
用法
正在获取特定参数/密钥:
query.get('param');
使用生成器获取整个对象:
var storage = query.build();
console.log(storage.param);
还有很多。。。查看github链接以获取更多示例。
特征
解码和参数缓存支持哈希查询字符串#hello?第3页支持传递自定义查询支持数组/对象参数user[]=“jim”&user[]=”bob“支持空管理&&支持不带值的声明参数name&hello=“world”支持重复参数param=1¶m=2干净、紧凑、可读的源4kbAMD,需要,节点支持
如果您使用的是jQuery,那么可以使用一个库,例如jQueryBBQ:返回按钮和查询库。
…jQueryBBQ提供了一个完整的.depam()方法,以及哈希状态管理、片段/查询字符串解析和合并实用程序方法。
编辑:添加参数示例:
var DeparamExample=函数(){var params=$.depam.querystring();//nameofram是来自url的参数的名称//如果ajax使用哈希刷新,下面的代码将获取参数if(typeof params.nameofram==“undefined”){params=jQuery.departam.frage(window.location.href);}if(typeof params.nameofram!=“undefined”){var paramValue=params.nameofram.toString();}};
如果您只想使用纯JavaScript,可以使用。。。
var getParamValue = (function() {
var params;
var resetParams = function() {
var query = window.location.search;
var regex = /[?&;](.+?)=([^&;]+)/g;
var match;
params = {};
if (query) {
while (match = regex.exec(query)) {
params[match[1]] = decodeURIComponent(match[2]);
}
}
};
window.addEventListener
&& window.addEventListener('popstate', resetParams);
resetParams();
return function(param) {
return params.hasOwnProperty(param) ? params[param] : null;
}
})();
由于新的HTML历史API,特别是History.pushState()和History.replaceState(),URL可能会发生更改,这将使参数及其值的缓存无效。
此版本将在每次更改历史记录时更新其内部参数缓存。
Node.js的源代码中有一个健壮的实现https://github.com/joyent/node/blob/master/lib/querystring.js
TJ的qs也执行嵌套参数解析https://github.com/visionmedia/node-querystring
代码高尔夫:
var a = location.search&&location.search.substr(1).replace(/\+/gi," ").split("&");
for (var i in a) {
var s = a[i].split("=");
a[i] = a[unescape(s[0])] = unescape(s[1]);
}
显示它!
for (i in a) {
document.write(i + ":" + a[i] + "<br/>");
};
在我的Mac上:test.htm?i=can&has=cheezburg显示屏
0:can
1:cheezburger
i:can
has:cheezburger
var getUrlParameters = function (name, url) {
if (!name) {
return undefined;
}
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
url = url || location.search;
var regex = new RegExp('[\\?&#]' + name + '=?([^&#]*)', 'gi'), result, resultList = [];
while (result = regex.exec(url)) {
resultList.push(decodeURIComponent(result[1].replace(/\+/g, ' ')));
}
return resultList.length ? resultList.length === 1 ? resultList[0] : resultList : undefined;
};