【发布时间】:2018-06-13 11:22:49
【问题描述】:
我正在使用 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 指南。 请帮忙。谢谢
【问题讨论】:
标签: ruby-on-rails json ajax ruby-on-rails-5.2