我一直在尝试创建 3 个动态下拉列表,其中第一个更改第二个的内容,第二个更改第三个的内容。
我还没有找到这样做的示例,我找到了一个示例,其中您将所有信息发送给客户端并在那里进行过滤,但这不是我想要的。我希望它在每次选择发生变化时与服务器交互。
如果有人有教程或可以举一个简短的例子,我将不胜感激
谢谢
我一直在尝试创建 3 个动态下拉列表,其中第一个更改第二个的内容,第二个更改第三个的内容。
我还没有找到这样做的示例,我找到了一个示例,其中您将所有信息发送给客户端并在那里进行过滤,但这不是我想要的。我希望它在每次选择发生变化时与服务器交互。
如果有人有教程或可以举一个简短的例子,我将不胜感激
谢谢
你需要 3 件事让它工作:
1-您选择的更改事件的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 Ajax 控制器功能:
// 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