3
我一直在嘗試創建3個動態下拉列表,第一個更改第二個內容,第二個更改第三個內容。Ruby on Rails的動態下拉列表(select_tag)
我還沒有找到一個這樣做的例子,我發現了一個例子,你將所有的信息發送到客戶端,並在那裏被過濾,但它不是我想要的。 我希望它在每次選擇發生變化時都與服務器進行交互。
如果有人有教程或可以給一個簡單的例子,我會很感激的是
感謝
我一直在嘗試創建3個動態下拉列表,第一個更改第二個內容,第二個更改第三個內容。Ruby on Rails的動態下拉列表(select_tag)
我還沒有找到一個這樣做的例子,我發現了一個例子,你將所有的信息發送到客戶端,並在那裏被過濾,但它不是我想要的。 我希望它在每次選擇發生變化時都與服務器進行交互。
如果有人有教程或可以給一個簡單的例子,我會很感激的是
感謝
你需要三樣東西,它的工作:
的Javascript上的改變事件對你的選擇:
// This will monitor your select control and start the process after its content has changed
$('select#my_select_control').change(select_has_changed(this));
2-阿賈克斯的Javascript控制器功能:
// This will send the selected value to your Rails server
function select_has_changed(obj)
{
// We get the selected value
var value = $(obj).val();
// It's a good idea here to verify the value.
// For example if the value is empty we can empty the content
// of the target select control and do not go through ajax
// We make the ajax call to the rails controller
$.ajax({url: '/path/to/controller/action',
data: {value: value},
// We are requesting for json response, but you can use html if you like
dataType: "json",
// Get method, or other is you like, you just have to
// define it accordingly in your routes
method: 'get'
// This is the function to call when ajax succeed
success: function (data) { fill_up_form(data, obj) }
});
}
// This is called when Ajax was successful , and it will
// fill up your target select control
function fill_up_form(data, obj)
{
content = ... // Here you loop through your json data to create
// a set of OPTION tags
// Or if you used html as dataType, the rails server had it done
// so you can inject directly in your select target control
$('select#my_target_control').html(content);
}
3- Rails的控制器方法
# The action method that receive the ajax call
# you must have set-up your routes accordingly
def get_my_ajax_data
# This fetches the data from the database
# Note that we are using `params` with the same index as
# we used in the `data` hash of the ajax call
# which, in my example is `value`
records = Model.where(field: params[:value])
# For a json request we return a collection of [id, text]
# that can be used to populate your target select control
# As an alternative we could have render a template if
# we was requesting for html content
render json: records.collect{ |r| {id: r.id, text: r.name} }
end
我沒有未來,但不得以任何理由代碼失敗,並update_cities_options功能則不會調用,問題是在ajax部分,但我不知道在哪裏
function findCities(obj){ var value = $(obj).val(); $.ajax({ url: url_for(:controller=>'state', :action=>'find_cities'), data: {value: value}, dataType: "json", method: 'get', success: function (data) { update_cities_options(data, obj) } }); }
– Leo你不能在你的js文件中使用'url_for'。你可以對它進行硬編碼(不可取,但對於測試足夠好),那麼當它工作時,你可以看看這個庫https://github.com/gazay/gon輕鬆地將vars從rails傳遞給js – Benj