如何在 URI 中访问多个键值



我遇到了我采用相同字段类型的多个输入来呈现表单的情况。

为了给出一些背景:

GET post_ad_form/?tree_field=brand;brand=bmw&tree_field=country;country=India

我需要分别返回品牌"bmw"的模型和国家"India"的城市。

该结构基于"如何为 HTTP GET 的多个键值参数设计 REST URI">

如何访问params['tree_field']

你可以结合URI#parseCGI#parse来获取参数:

require 'cgi'
require 'uri'
url = 'post_ad_form/?tree_field=brand;brand=bmw&tree_field=country;country=India'
queries = CGI.parse(URI.parse(url).query)
#=> {"tree_field"=>["brand", "country"], "brand"=>["bmw"], "country"=>["India"]}
queries['tree_field'] #=> ["brand", "country"]

但是,如果您只是在字符串中具有参数,则可以使用CGI#parse

params = 'tree_field=brand;brand=bmw&tree_field=country;country=India'
CGI.parse(params)
#=> {"tree_field"=>["brand", "country"], "brand"=>["bmw"], "country"=>["India"]}

您的问题尚不清楚,但也许这会有所帮助:

require 'uri'
uri = URI.parse('http://somehost.com/post_ad_form/?tree_field=brand;brand=bmw&tree_field=country;country=India')
query = URI.decode_www_form(uri.query).map{ |a| a.last[/;(.+)$/, 1].split('=') }.to_h # => {"brand"=>"bmw", "country"=>"India"}

分解为:

query = URI.decode_www_form(uri.query)       # => [["tree_field", "brand;brand=bmw"], ["tree_field", "country;country=India"]]
  .map{ |a| a.last[/;(.+)$/, 1].split('=') } # => [["brand", "bmw"], ["country", "India"]]
  .to_h                                      # => {"brand"=>"bmw", "country"=>"India"}

相关内容

  • 没有找到相关文章

最新更新