是否有一种通过jQuery(或不使用)检索查询字符串值的无插件方法?
如果是,怎么办?如果没有,是否有插件可以这样做?
是否有一种通过jQuery(或不使用)检索查询字符串值的无插件方法?
如果是,怎么办?如果没有,是否有插件可以这样做?
当前回答
我认为这是实现这一点的准确和简洁的方法(修改自http://css-tricks.com/snippets/javascript/get-url-variables/):
function getQueryVariable(variable) {
var query = window.location.search.substring(1), // Remove the ? from the query string.
vars = query.split("&"); // Split all values by ampersand.
for (var i = 0; i < vars.length; i++) { // Loop through them...
var pair = vars[i].split("="); // Split the name from the value.
if (pair[0] == variable) { // Once the requested value is found...
return ( pair[1] == undefined ) ? null : pair[1]; // Return null if there is no value (no equals sign), otherwise return the value.
}
}
return undefined; // Wasn't found.
}
其他回答
这里发布的一些解决方案效率低下。每次脚本需要访问参数时重复正则表达式搜索是完全不必要的,一个函数将参数拆分为关联数组样式对象就足够了。如果您不使用HTML5历史API,则每次加载页面只需要一次。这里的其他建议也无法正确解码URL。
var urlParams;
(window.onpopstate = 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);
urlParams = {};
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
})();
示例查询字符串:
?i=main&mode=front&sid=de8d49b78a85a322c4155015fdce22c4&enc=+Hello%20&empty
结果:
urlParams = {
enc: " Hello ",
i: "main",
mode: "front",
sid: "de8d49b78a85a322c4155015fdce22c4",
empty: ""
}
alert(urlParams["mode"]);
// -> "front"
alert("empty" in urlParams);
// -> true
这也可以很容易地改进为处理数组样式的查询字符串。这里有一个这样的例子,但由于RFC 3986中没有定义数组样式参数,所以我不会用源代码污染这个答案。对于那些对“污染”版本感兴趣的人,请看下面坎贝尔的答案。
此外,正如评论中指出的;是key=value对的合法分隔符。它需要更复杂的正则表达式来处理;或&,我认为这是不必要的,因为这很少见;我想说,更不可能两者都使用。如果您需要支持;而不是&,只是在正则表达式中交换它们。
<script>var urlParams = <?php echo json_encode($_GET, JSON_HEX_TAG);?>;</script>
简单多了!
#已更新
一个新的功能是检索重复的参数,如下myparam=1和myparam=2。然而,没有一个规范,目前的大多数方法都遵循数组的生成。
myparam = ["1", "2"]
因此,这是管理它的方法:
let urlParams = {};
(window.onpopstate = function () {
let 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)) {
if (decode(match[1]) in urlParams) {
if (!Array.isArray(urlParams[decode(match[1])])) {
urlParams[decode(match[1])] = [urlParams[decode(match[1])]];
}
urlParams[decode(match[1])].push(decode(match[2]));
} else {
urlParams[decode(match[1])] = decode(match[2]);
}
}
})();
这些都是很好的答案,但我需要一些更强大的东西,我想你们可能都想拥有我创造的东西。
这是一种简单的库方法,可以对URL参数进行剖析和操作。静态方法有以下子方法,可以在主题URL上调用:
获取主机获取路径获取哈希setHash获取参数获取查询setParam(设置参数)获取参数hasParamremoveParam(删除参数)
例子:
URLParser(url).getParam('myparam1')
var url = "http://www.example.com/folder/mypage.html?myparam1=1&myparam2=2#something";
function URLParser(u){
var path="",query="",hash="",params;
if(u.indexOf("#") > 0){
hash = u.substr(u.indexOf("#") + 1);
u = u.substr(0 , u.indexOf("#"));
}
if(u.indexOf("?") > 0){
path = u.substr(0 , u.indexOf("?"));
query = u.substr(u.indexOf("?") + 1);
params= query.split('&');
}else
path = u;
return {
getHost: function(){
var hostexp = /\/\/([\w.-]*)/;
var match = hostexp.exec(path);
if (match != null && match.length > 1)
return match[1];
return "";
},
getPath: function(){
var pathexp = /\/\/[\w.-]*(?:\/([^?]*))/;
var match = pathexp.exec(path);
if (match != null && match.length > 1)
return match[1];
return "";
},
getHash: function(){
return hash;
},
getParams: function(){
return params
},
getQuery: function(){
return query;
},
setHash: function(value){
if(query.length > 0)
query = "?" + query;
if(value.length > 0)
query = query + "#" + value;
return path + query;
},
setParam: function(name, value){
if(!params){
params= new Array();
}
params.push(name + '=' + value);
for (var i = 0; i < params.length; i++) {
if(query.length > 0)
query += "&";
query += params[i];
}
if(query.length > 0)
query = "?" + query;
if(hash.length > 0)
query = query + "#" + hash;
return path + query;
},
getParam: function(name){
if(params){
for (var i = 0; i < params.length; i++) {
var pair = params[i].split('=');
if (decodeURIComponent(pair[0]) == name)
return decodeURIComponent(pair[1]);
}
}
console.log('Query variable %s not found', name);
},
hasParam: function(name){
if(params){
for (var i = 0; i < params.length; i++) {
var pair = params[i].split('=');
if (decodeURIComponent(pair[0]) == name)
return true;
}
}
console.log('Query variable %s not found', name);
},
removeParam: function(name){
query = "";
if(params){
var newparams = new Array();
for (var i = 0;i < params.length;i++) {
var pair = params[i].split('=');
if (decodeURIComponent(pair[0]) != name)
newparams .push(params[i]);
}
params = newparams;
for (var i = 0; i < params.length; i++) {
if(query.length > 0)
query += "&";
query += params[i];
}
}
if(query.length > 0)
query = "?" + query;
if(hash.length > 0)
query = query + "#" + hash;
return path + query;
},
}
}
document.write("Host: " + URLParser(url).getHost() + '<br>');
document.write("Path: " + URLParser(url).getPath() + '<br>');
document.write("Query: " + URLParser(url).getQuery() + '<br>');
document.write("Hash: " + URLParser(url).getHash() + '<br>');
document.write("Params Array: " + URLParser(url).getParams() + '<br>');
document.write("Param: " + URLParser(url).getParam('myparam1') + '<br>');
document.write("Has Param: " + URLParser(url).hasParam('myparam1') + '<br>');
document.write(url + '<br>');
// Remove the first parameter
url = URLParser(url).removeParam('myparam1');
document.write(url + ' - Remove the first parameter<br>');
// Add a third parameter
url = URLParser(url).setParam('myparam3',3);
document.write(url + ' - Add a third parameter<br>');
// Remove the second parameter
url = URLParser(url).removeParam('myparam2');
document.write(url + ' - Remove the second parameter<br>');
// Add a hash
url = URLParser(url).setHash('newhash');
document.write(url + ' - Set Hash<br>');
// Remove the last parameter
url = URLParser(url).removeParam('myparam3');
document.write(url + ' - Remove the last parameter<br>');
// Remove a parameter that doesn't exist
url = URLParser(url).removeParam('myparam3');
document.write(url + ' - Remove a parameter that doesn\"t exist<br>');
获取查询的一行代码:
var value = location.search.match(new RegExp(key + "=(.*?)($|\&)", "i"))[1];
如果您使用Browserify,则可以使用Node.js中的url模块:
var url = require('url');
url.parse('http://example.com/?bob=123', true).query;
// returns { "bob": "123" }
进一步阅读:URL Node.js v0.12.2手册和文档
编辑:您可以使用URL界面,它在几乎所有新浏览器中都被广泛采用,如果代码将在旧浏览器上运行,您可以使用像这样的polyfill。下面是一个关于如何使用URL接口获取查询参数(也称为搜索参数)的代码示例
const url = new URL('http://example.com/?bob=123');
url.searchParams.get('bob');
您也可以使用URLSearchParams进行搜索,下面是MDN的一个使用URLSearchParams进行搜索的示例:
var paramsString = "q=URLUtils.searchParams&topic=api";
var searchParams = new URLSearchParams(paramsString);
//Iterate the search parameters.
for (let p of searchParams) {
console.log(p);
}
searchParams.has("topic") === true; // true
searchParams.get("topic") === "api"; // true
searchParams.getAll("topic"); // ["api"]
searchParams.get("foo") === null; // true
searchParams.append("topic", "webdev");
searchParams.toString(); // "q=URLUtils.searchParams&topic=api&topic=webdev"
searchParams.set("topic", "More webdev");
searchParams.toString(); // "q=URLUtils.searchParams&topic=More+webdev"
searchParams.delete("topic");
searchParams.toString(); // "q=URLUtils.searchParams"
如果您有Undercore.js或lodash,一种快速而肮脏的方法是:
_.object(window.location.search.slice(1).split('&').map(function (val) { return val.split('='); }));