是否有一种通过jQuery(或不使用)检索查询字符串值的无插件方法?
如果是,怎么办?如果没有,是否有插件可以这样做?
是否有一种通过jQuery(或不使用)检索查询字符串值的无插件方法?
如果是,怎么办?如果没有,是否有插件可以这样做?
当前回答
下面是String原型实现:
String.prototype.getParam = function( str ){
str = str.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp( "[\\?&]*"+str+"=([^&#]*)" );
var results = regex.exec( this );
if( results == null ){
return "";
} else {
return results[1];
}
}
示例调用:
var status = str.getParam("status")
str可以是查询字符串或url
其他回答
试试看:
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。。。将其移动到函数并将字符串作为参数传递
Node.js的源代码中有一个健壮的实现https://github.com/joyent/node/blob/master/lib/querystring.js
TJ的qs也执行嵌套参数解析https://github.com/visionmedia/node-querystring
在简单的JavaScript代码中保持简单:
function qs(key) {
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[key];
}
从JavaScript代码中的任何位置调用它:
var result = qs('someKey');
有很多方法可以检索URI查询值,我更喜欢这个方法,因为它很短,而且效果很好:
function get(name){
if(name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec(location.search))
return decodeURIComponent(name[1]);
}
我使用这里列出的技术开发了一个小型库,以创建一个易于使用的解决方案;可以在这里找到:
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,需要,节点支持