0
我一直在努力弄清楚爲什麼我得到空陣列,並沒有得到結果回城市時選擇狀態。我遵循博客文章blog post,我添加了一個我在最後閱讀的建議,並想知道這是否是一種更可行的方式來實現它,以及如何這樣做。你能給我最好的解決辦法嗎?爲什麼我的Javascript返回null爲城市記錄當我選擇我的國家在Rails應用程序,使用城市狀態gem
我用我的紅寶石寶石城邦city state gem
在我的形式我有以下幾點:(加在一個頁面中的JavaScript和表單標籤,便於閱讀本論壇)
形式摘錄
<div class ="form-group">
<select id="states-of-country" name="project[state]">
<option value="" selected="">Select Your State</option>
<% CS.states(:us).each do |key, value| %>
<option value="<<%= key %>>"><%= value %></option>
<% end %>
</select>
</div>
<div class="form-group">
<select id="cities-of-state" name="project[city]">
<option value="" selected="">Select Your City</option>
</select>
</div>
的Javascript
$('#states-of-country').change(function() {
var input_state = $(this);
var cities_of_state = $("#cities-of-state");
if ($(this).val() == "") {
cities_of_state.html("");
} else {
$.getJSON('/cities/' + $(this).val(), function (data) {
// cities_of_state.empty();
var opt = '<option value="" selected="">Select Your City</option>';
console.log(data);
if (data.length == 0) {} else {
data.forEach(function (i) {
opt += '<option value="+ i +">' + i + '</option>';
cities_of_state.html(opt);
});
}
});
}
});
路線s.rb
get 'cities/:state', to: 'application#cities'
當我進入我的平臺,然後選擇我得到[] 的console.log(數據)的返回狀態;數據是空的...任何人都可以指向正確的方向...>?
博客上的某人提到了以下建議以使其更容易,但您如何實現該建議? blog post
你只需要把這樣的事情:
class Model < ActiveRecord::Base
##your attributes and associations
## your methods
## ..............
def self.get_countries
CS.get
end
def self.get_states(country_code)
CS.get country_code.to_sym
end
def self.get_cities(state_code)
CS.get :us state_code.to_sym
end
end