如何从 Rails 中的 URL 获取查询字符串 [英] How to get a query string from a URL in Rails
本文介绍了如何从 Rails 中的 URL 获取查询字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法在 Rails 中获取传递的 URL 字符串中的查询字符串?
Is there is a way to get the query string in a passed URL string in Rails?
我想传递一个 URL 字符串:
I want to pass a URL string:
http://www.foo.com?id=4&empid=6
如何获取id
和empid
?
推荐答案
如果您在字符串中有一个 URL,那么使用 URI 和 CGI 将其分开:
If you have a URL in a string then use URI and CGI to pull it apart:
url = 'http://www.example.com?id=4&empid=6'
uri = URI.parse(url)
params = CGI.parse(uri.query)
# params is now {"id"=>["4"], "empid"=>["6"]}
id = params['id'].first
# id is now "4"
这些东西请使用标准库,不要尝试自己用正则表达式来做.
Please use the standard libraries for this stuff, don't try and do it yourself with regular expressions.
另见 Quv 对下面 Rack::Utils.parse_query
的评论.
Also see Quv's comment about Rack::Utils.parse_query
below.
参考文献:
更新:这些天我可能会使用 Addressable::Uri
而不是标准库中的 URI
:
Update: These days I'd probably be using Addressable::Uri
instead of URI
from the standard library:
url = Addressable::URI.parse('http://www.example.com?id=4&empid=6')
url.query_values # {"id"=>"4", "empid"=>"6"}
id = url.query_values['id'] # "4"
empid = url.query_values['empid'] # "6"
这篇关于如何从 Rails 中的 URL 获取查询字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文