dongxing4805 2016-04-04 18:49
浏览 48

Javascript / jQuery URL查询参数解析

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条回答 默认 最新

  • doubu1964 2016-04-04 20:22
    关注

    Figured it out:

    I used URL.js to get the query parameters using URI(location.href).query(true)

    I get an object with a few properties, including "view-mode" and "filters[one]=1&filters[two]=2" where "filters[one]=1&filters[two]=2" is an object (based on the way URL.js parses the query).

    Then I iterate through the object and check if the property is an object. If it is, I use Ben Alman's BBQ jQuery Plugin to parse the property name which turns:

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

    into:

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

    The URI.js parsing method also results in a few properties that have no value such as "*filters[one]=1&filters[two]=21*" and "*filters[one]=1&filters[two]=2[]*". I ignore those.

    Then I can combine the original properties that aren't objects such as "view-mode=grid" with the parsed properties that are objects, such as "filters%5Bone%5D%3D1%26filters%5Btwo%5D%3D2" and I end up with:

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

    End result is that both Javascript and PHP can read and understand the query parameters.

    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条