javascript - 将 json 参数传递给rails api

标签 javascript jquery ruby-on-rails ruby

我正在使用 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/

相关文章:

javascript - Html 倒计时器在页面重新加载时不起作用

javascript - 我们如何才能只更改网页的内部部分?

javascript - 有一个元素随页面滚动, "snap"沿途锚定吗?

mysql - Rails 中的多个数据库连接

javascript - 使用窗口对象和对象 key 对调用 JavaScript 值

javascript - AngularJS JavaScript 登录语法错误

javascript - 无法使用 jQuery 访问页面表单和 iframe 表单

javascript - 主干模型 : Ajax request in parse override

ruby-on-rails - 最简单的文件服务方式 - Ruby on Rails

javascript - 使用浏览器历史记录时,Rails link_to Remote True 问题