Javascript / jQuery URL Query Params Parse

时间:2016-04-04 18:49:49

标签: javascript php jquery url parameters

I have a URL query that looks like this:

view-mode=grid&filters%5Bone%5D%3D1%26filters%5Btwo%5D%3D2

Ultimately I want to be able to parse the parameters in both PHP and Javascripting (using jQuery). No issues parsing in PHP using $_GET. Trying to figure out how to do it using Javascript. The final object in Javascript should look like this:

{ "view-mode" : "grid", "filters" : { "one" : "1", "two" : "2" } }

Any suggestions? I am using URI.js for some building and parsing already.

Thanks

1 个答案:

答案 0 :(得分:0)

想出来:

我使用URL.js来获取查询参数 URI(location.href).query(true)

我得到一个包含一些属性的对象,包括“ 查看模式 ”和“ 过滤器[one] = 1&过滤器[两个] ] = 2 “其中” 过滤器[one] = 1& filters [two] = 2 “是一个对象(基于方式) URL.js解析查询)。

然后我遍历该对象并检查该属性是否是一个对象。如果是,我使用Ben Alman's BBQ jQuery Plugin来解析转为的属性名称:

filters%5Bone%5D%3D1%26filters%5Btwo%5D%3D2

成:

{ "filters" : { "one" : "1", "two" : "2" } }

URI.js解析方法还会导致一些没有值的属性,例如“ * filters [one] = 1& filters [two] = 2 1 * “和” *过滤器[one] = 1& filters [two] = 2 [] * “。我忽略了这些。

然后我可以将不是对象的原始属性(例如“ view-mode = grid ”)与作为对象的已解析属性组合在一起,例如“< strong> 过滤器%5Bone%5D%3D1%26filters%5B2%5D%3D2 “我最终得到:

{ "view-mode" : "grid", "filters" : { "one" : "1", "two" : "2" } }

最终结果是Javascript和PHP都可以读取和理解查询参数。