如何从 Rails 中的 URL 获取查询字符串

编程入门 行业动态 更新时间:2024-10-21 12:36:39
本文介绍了如何从 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:

www.foo?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 = 'www.example?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.

参考文献:

  • CGI.parse
  • URI.parse

更新:这些天我可能会使用 Addressable::Uri 而不是标准库中的 URI :

Update: These days I'd probably be using Addressable::Uri instead of URI from the standard library:

url = Addressable::URI.parse('www.example?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 获取查询字符串

本文发布于:2023-11-17 12:07:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1609950.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   Rails   URL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!