我正在使用Rails 5.2,并希望有一个国家和城市选择表单。我使用city-state gem来创建下拉菜单,其中包含所有国家和城市,但是城市下拉菜单需要事先知道所选的国家。
我认为最好使用ajax来通过下拉菜单上的输入事件监听器传递所选国家。但是我的问题是,ajax请求没有传递我编写的JSON变量,而是传递了
目前我的代码如下:
以下是请求后在控制台中看到的内容:
我认为最好使用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指南。请帮忙。谢谢。