4

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

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

   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)

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

4

3 回答 3

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){...}
})

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

mydata = 'thing[field1]=value1&thing[field2]=value2'

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

 Parameters: {"thing"=>{"field1"=>"value1", "field2"=>"value2"}, "id"=>"1"}

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

于 2018-06-13T21:04:06.440 回答
2

我遇到了类似的问题。然后我了解了所有现代浏览器都支持的URLSearchParams接口。

Rails.ajax({
  type: 'GET',
  url: '/users/' + <%= params[:id] %> + '/country',
  data: new URLSearchParams({'country': country}).toString(),
  success: function (response) {
    // ...
  }
})
于 2019-07-17T07:26:21.650 回答
1

JSON.stringify()在您的数据上使用:

data: JSON.stringify({'country': country}),

您当前通过调用而不是 JSON 传递对象,这导致了问题。我很确定这会为你解决问题。

您的id参数很好,因为它通过 URL 传递,但数据本身需要作为 JSON 字符串传递。

于 2018-06-13T12:21:24.527 回答