window.location.search 查询为 JSON
有没有更好的方法将 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]; });
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.
var query = window.location.search.substring(1), queryPairs = query.split('&'), queryJSON = {};
$.each(queryPairs, function() { queryJSON[this.split('=')[0]] = this.split('=')[1]; });
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(13)
另请注意,有一个 api 可用于查询/操作搜索参数:
https://developer.mozilla.org/en-US/docs/Web /API/URLSearchParams
Please also note that there's an api to query/manipulate search params with:
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
这是一个纯 JS 函数。解析当前 URL 的搜索部分并返回一个对象。 (注意,为了可读性,这有点冗长。)
在相关说明中,您并不是试图将单个参数存储在“JSON”中,而是存储在“对象”中。 ;)
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.)
On a related note, you're not trying to store the single parameters in "a JSON" but in "an object". ;)
对于简单情况来说可能是最短的解决方案:
Probably the shortest solution for simple cases:
如果您使用现代浏览器,这会产生与接受的答案相同的结果:
If you are using modern browser this produce the same result as accepted answer:
我的方法,简单干净
My approach, simple and clean
只是想使用一些 ESNext 和减速器来分享这个解决方案。
它的功能与 @Carlo 建议的几乎相同,但如果您熟悉 ES6 和减速器,它会更干净一些。
Just wanted to share this solution using a bit of ESNext and a reducer.
It does pretty much the same suggested by @Carlo but it's a bit cleaner if you're comfortable with ES6 and reducers.
在 @rafaelbiten 的 ES6 工作的基础上,我添加了对没有值的参数和重复条目样式的查询参数数组的支持。
JSFiddle: https://jsfiddle.net/w922xefs/
Building on @rafaelbiten's ES6 work, I added support for params that have no value and query param arrays of the duplicate entry style.
JSFiddle: https://jsfiddle.net/w922xefs/
stringify 之后的 JSON Parse 完成将数组数据转换为 json 的工作。
?key1=val1&key2[]=val2.1&key2[]=val2.2&key2[]=val2.3&
JSON Parse after stringify does the job of converting to a json with array data.
?key1=val1&key2[]=val2.1&key2[]=val2.2&key2[]=val2.3&
注意 --毫无疑问,上述解决方案有效,但它不会涵盖所有运算符
我猜你会想要这样的东西
- 例如 -
覆盖搜索@1st行
用你得到的输出
Note --No doubt above solution works, but it wont cover all the operators
Guess you would want something like this-
ex -
Override search @1st line with
Output you get is
如果有人只是想访问搜索查询参数,请使用此功能:
易于使用,只需调用
getQueryStringValue(term)
In case someone is looking just to access the search query parameters, use this function:
Easy to use just call
getQueryStringValue(term)
我改进了 @Carlo Zottmann 的解决方案,以实现键的多个值。例如,您有这样的查询:
它产生结果:
解决方案:
I improved @Carlo Zottmann's solution for multiple value for a key. For example you have query like this:
it produces the result:
Solution:
你可以这样做
you can do this