Rails 使用 JSON 通过 ajax 请求传递参数

Lau*_*nce 4 ajax json ruby-on-rails ruby-on-rails-5.2

我正在使用 rails 5.2 并且我想要一个国家和城市选择表。我正在使用城邦 gem 来创建包含所有国家和城市的下拉列表,但是,城市下拉列表需要事先知道选择的国家/地区。

我认为最好使用 ajax 在下拉列表中使用输入事件侦听器传递选定的国家/地区。

我的问题是 ajax 请求没有传递我正在编写的 JSON 变量,但它传递了 {"object Object"=>nil, "id"=>"1"}.

这就是我现在所拥有的:

    <%= form_with(model: @user) do |form| %>
    <%= form.select :country, CS.countries.values.sort, { :prompt => 'Country'} %>
    <%= form.select :city, CS.states('placeholder').keys.flat_map { |state| CS.cities(state, 'placeholder') }, { :prompt => 'City'} %>
    <%= form.submit %>
<% end %>

<script>
    var countryForm = document.getElementById('user_country');
    countryForm.addEventListener('input', function (evt) {
    var country = this.value;
    Rails.ajax({
        type: "GET",
        url: '/users/' + <%= params[:id] %> + '/country',
        dataType:'json',
        data : {'country': country},
        error: function (xhr, status, error) {
            console.log('error')
            console.error('AJAX Error: ' + status + error);
        },
        success: function (response) {
        }
    });
});
</script>
Run Code Online (Sandbox Code Playgroud)

这是我在请求后在控制台中看到的:

   Started GET "/users/1/country?[object%20Object]" for 127.0.0.1 at 2018-06-13 13:19:50 +0200
Processing by UsersController#country as JSON
  Parameters: {"object Object"=>nil, "id"=>"1"}
Completed 204 No Content in 1ms (ActiveRecord: 0.0ms)
Run Code Online (Sandbox Code Playgroud)

知道我做错了什么吗?我试过到处寻找,但没有看到任何关于如何在 Ajax 中使用 JSON 的 rails 5 指南。请帮忙。谢谢

Lau*_*nce 6

到处搜索后在此链接上找到了解决方案:https : //learnetto.com/blog/how-to-make-ajax-calls-in-rails-5-1-with-or-without-jquery

请求的代码可以这样写:

Rails.ajax({
  type: "POST", 
  url: "/things",
  data: mydata,
  success: function(repsonse){...},
  error: function(repsonse){...}
})
Run Code Online (Sandbox Code Playgroud)

除了一件事!据我所知,您不能简单地发送 JSON 数据。所以我们需要像这样手动将 mydata 转换为 application/x-www-form-urlencoded 内容类型:

mydata = 'thing[field1]=value1&thing[field2]=value2'
Run Code Online (Sandbox Code Playgroud)

这样做时,我以正确的方式获取参数:

 Parameters: {"thing"=>{"field1"=>"value1", "field2"=>"value2"}, "id"=>"1"}
Run Code Online (Sandbox Code Playgroud)

显然,在 jquery 时代发生了数据对象的自动转换,但在 rails-ujs 版本中却没有。