辛纳屈和问号 [英] Sinatra and question mark

查看:22
本文介绍了辛纳屈和问号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要用 Sinatra 制作一些方法,看起来应该是这样的:

I need to make some methods with Sinatra that should look like:

http//:localhost:1234/add?string_to_add

http//:localhost:1234/add?string_to_add

但是当我这样声明时:

get "/add?:string_to_add" do
...
end

它没有看到 string_to_add 参数.

我应该如何声明我的方法并使用这个参数来使事情工作?

How should I declare my method and use this parameter to make things work?

推荐答案

在 URL 中,问号分隔 path 来自查询 部分.查询部分通常由名称/值对组成,通常由 Web 浏览器构建以匹配用户在表单中输入的数据.例如,网址可能如下所示:

In a URL, a question mark separates the path part from the query part. The query part normally consists of name/value pairs, and is often constructed by a web browser to match the data a user has entered into a form. For example a url might look like:

http://example.com/submit?name=John&age=93

这里是/submit中的路径部分,查询部分是name=John&age=93,它指的是的值John"name 键,age 为93".

Here the path section in /submit, and the query sections is name=John&age=93 which refers to the value "John" for the name key, and "93" for the age.

当您在 Sinatra 中创建路线时,您只需指定路径部分.Sinatra 然后解析查询,并在 params 对象中提供其中的数据.在本例中,您可以执行以下操作:

When you create a route in Sinatra, you only specify the path part. Sinatra then parses the query, and makes the data in it available in the params object. In this example you could do something like this:

get '/submit' do
  name = params[:name]
  age = params[:age]
  # use name and age variables
  ...
end

如果在定义 Sinatra 路由时使用 ? 字符,它将使 url 的一部分成为可选的.在您使用的示例中 (get "/add?:string_to_add"),它实际上会匹配任何以 /ad 开头的 url,然后可选地匹配另一个 d,然后将其他任何内容放入 params 哈希的 :string_to_add 键中,查询部分将单独解析.换句话说,问号使前面的 d 字符可选.

If you use a ? character when defining a Sinatra route, it makes part of the url optional. In the example you used (get "/add?:string_to_add"), it will actually match any url starting with /ad, then optionally another d, and then anything else will be put in the :string_to_add key of the params hash, and the query section will be parsed separately. In other words the question mark makes the preceding d character optional.

如果您想在 Sinatra 中获取查询字符串的原始"文本,您可以使用 request 对象的query_string 方法.在您的示例中,它看起来像这样:

If you want to get the ‘raw’ text of the query string in Sinatra, you can use the query_string method of the request object. In your example that would look something like this:

get '/add' do
  string_to_add = request.query_string
  ...
end

请注意,路由不包含 ? 字符,只包含基本的 /add.

Note that the route doesn’t include the ? character, just the base /add.

这篇关于辛纳屈和问号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆