jQuery window.location.search 查询为 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6539761/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
window.location.search query as JSON
提问by thugsb
Is there a better way to convert a URL's location.search as an object? Maybe just more efficient or trimmed down? I'm using jQuery, but pure JS can work too.
有没有更好的方法将 URL 的 location.search 转换为对象?也许只是更有效或减少?我正在使用 jQuery,但纯 JS 也可以工作。
var query = window.location.search.substring(1), queryPairs = query.split('&'), queryJSON = {};
$.each(queryPairs, function() { queryJSON[this.split('=')[0]] = this.split('=')[1]; });
回答by Carlo Zottmann
Here's a pure JS function. Parses the search part of the current URL and returns an object. (It's a bit verbose for readability, mind.)
这是一个纯 JS 函数。解析当前 URL 的搜索部分并返回一个对象。(注意,为了可读性,这有点冗长。)
function searchToObject() {
var pairs = window.location.search.substring(1).split("&"),
obj = {},
pair,
i;
for ( i in pairs ) {
if ( pairs[i] === "" ) continue;
pair = pairs[i].split("=");
obj[ decodeURIComponent( pair[0] ) ] = decodeURIComponent( pair[1] );
}
return obj;
}
On a related note, you're not trying to store the single parameters in "a JSON" but in "an object". ;)
在相关说明中,您不是尝试将单个参数存储在“JSON”中,而是存储在“对象”中。;)
回答by Ali Malekpour
If you are using modern browser this produce the same result as accepted answer:
如果您使用的是现代浏览器,这会产生与接受的答案相同的结果:
function searchToObject(search) {
return search.substring(1).split("&").reduce(function(result, value) {
var parts = value.split('=');
if (parts[0]) result[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]);
return result;
}, {})
}
回答by VyvIT
Please also note that there's an api to query/manipulate search params with: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
另请注意,有一个用于查询/操作搜索参数的 API:https: //developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
var params = new URLSearchParams(window.location.search)
for (let p of params) {
console.log(p);
}
回答by Clemens Helm
Probably the shortest solution for simple cases:
可能是简单情况的最短解决方案:
location.search
.slice(1)
.split('&')
.map(p => p.split('='))
.reduce((obj, [key, value]) => ({ ...obj, [key]: value }), {});
回答by Leonardo Ciaccio
My approach, simple and clean
我的方法,简单干净
var params = "?q=Hello World&c=Awesome";
params = "{\"" +
params
.replace( /\?/gi, "" )
.replace( /\&/gi, "\",\"" )
.replace( /\=/gi, "\":\"" ) +
"\"}";
params = JSON.parse( params );
alert( decodeURIComponent( params.q ) );
alert( decodeURIComponent( params.c ) );
回答by rafaelbiten
Just wanted to share this solution using a bit of ESNext and a reducer.
只是想使用一点 ESNext 和一个减速器来分享这个解决方案。
It does pretty much the same suggested by @Carlo but it's a bit cleaner if you're comfortable with ES6 and reducers.
它与@Carlo 建议的几乎相同,但如果您对 ES6 和减速器感到满意,它会更干净一些。
const urlSearchData = searchString => {
if (!searchString) return false;
return searchString
.substring(1)
.split('&')
.reduce((result, next) => {
let pair = next.split('=');
result[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
return result;
}, {});
};
const searchData = urlSearchData(window.location.search);
回答by Ricky C
Building on @rafaelbiten's ES6 work, I added support for params that have no value and query param arrays of the duplicate entry style.
基于@rafaelbiten 的 ES6 工作,我添加了对没有值的参数和重复条目样式的查询参数数组的支持。
JSFiddle: https://jsfiddle.net/w922xefs/
JSFiddle:https://jsfiddle.net/w922xefs/
const queryStringToJSObject = searchString => {
if (!searchString) return null;
return searchString
.replace(/^\?/, '') // Only trim off a single leading interrobang.
.split('&')
.reduce((result, next) => {
if (next === "") {
return result;
}
let pair = next.split('=');
let key = decodeURIComponent(pair[0]);
let value = typeof pair[1] !== "undefined" && decodeURIComponent(pair[1]) || undefined;
if (result.hasOwnProperty(key)) { // Check to see if this property has been met before.
if (Array.isArray(result[key])) { // Is it already an array?
result[key].push(value);
}
else { // Make it an array.
result[key] = [result[key], value];
}
}
else { // First time seen, just add it.
result[key] = value;
}
return result;
}, {}
);
};
// Simple read of query string
const searchData = queryStringToJSObject(window.location.search);
回答by Jeffery ThaGintoki
In case someone is looking just to access the search query parameters, use this function:
如果有人只想访问搜索查询参数,请使用此函数:
function getQueryStringValue (key)
{
return decodeURIComponent(window.location.search.replace(new RegExp("^(?:.*[&\?]" + encodeURIComponent(key).replace(/[\.\+\*]/g, "\$&") + "(?:\=([^&]*))?)?.*$", "i"), ""))
}
Easy to use just call getQueryStringValue(term)
易于使用只需调用 getQueryStringValue(term)
回答by Priya
JSON Parse after stringify does the job of converting to a json with array data.
stringify 后的 JSON Parse 完成将数组数据转换为 json 的工作。
?key1=val1&key2[]=val2.1&key2[]=val2.2&key2[]=val2.3&
?key1=val1&key2[]=val2.1&key2[]=val2.2&key2[]=val2.3&
{
'key1' : 'val1',
'key2' : [ 'val2.1', 'val2.2', 'val2.3' ]
}
function QueryParamsToJSON() {
var list = location.search.slice(1).split('&'),
result = {};
list.forEach(function(keyval) {
keyval = keyval.split('=');
var key = keyval[0];
if (/\[[0-9]*\]/.test(key) === true) {
var pkey = key.split(/\[[0-9]*\]/)[0];
if (typeof result[pkey] === 'undefined') {
result[pkey] = [];
}
result[pkey].push(decodeURIComponent(keyval[1] || ''));
} else {
result[key] = decodeURIComponent(keyval[1] || '');
}
});
return JSON.parse(JSON.stringify(result));
}
var query_string = QueryParamsToJSON();
回答by shubhamkes
Note--No doubt above solution works, but it wont cover all the operators
注意 -毫无疑问,上述解决方案有效,但它不会涵盖所有运营商
Guess you would want something like this-
猜猜你会想要这样的东西——
var search = location.search;
var trimmedSearch = search.substring(1);
var searchObj = trimmedSearch?JSON.parse(
'{"' + trimmedSearch.replace(/&/g, '","').replace(/=/g,'":"') + '"}',
function(key, value) {
return key===""?value:decodeURIComponent(value)
}
)
:
{}
console.log(searchObj);
ex -
前任 -
Override search @1st line with
覆盖搜索@第一行
search = "abc=foo&def=%5Basf%5D&xyz=5&foo=b%3Dar";
Output you get is
你得到的输出是
Object {abc: "foo", def: "[asf]", xyz: "5", foo: "b=ar"}