我正在使用 jquery 的 .ajax 方法对 ruby on Rails api 进行 get 调用。 get 调用的主体包含一个 bool 变量。然而,这个 bool 变量在 Rails 端不断转换为字符串。我在发出请求时使用了正确的 contentType。
这是我的 javascript ajax 调用:
var postBody = {male: true}
var request = $.ajax({
method: "GET",
url: "/biographies/getAll",
dataType: 'json',
contentType: 'application/json',
data: postBody
});
在 Ruby on Rails Controller 端,我使用:
params[:male]
但是 params[:male] 返回“true”字符串而不是 true bool 值。
根据 Ruby on Rails api:
If the "Content-Type" header of your request is set to "application/json", Rails will automatically convert your parameters into the params hash, which you can access as you would normally. http://guides.rubyonrails.org/action_controller_overview.html#json-parameters
有谁知道为什么它不会将 json 请求转换为 bool 值而是将其保留为字符串。
谢谢。
最佳答案
在 Rails 中,参数值始终是字符串; Rails 不会尝试猜测或转换类型。您必须修改代码逻辑以适应这种 Rails 行为。例如:
params[:male] == 'true'
参见this供引用。
关于javascript - 将 json 参数传递给rails api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33487679/