[英]Replace content of select2 dropdown with data from ajax call
我有一个带有两个下拉菜单的Rails应用程序。 当第一个被选中为“作者”时,它将进行ajax调用以检索作者的书。 自动预订电话。
在JavaScript中,我有: $.ajax(type: 'GET', url: myadress)
。
它呈现一个.js.erb
文件:
var dropdown = "<%= escape_javascript(select_tag :author_book, options_from_collection_for_select(@books, :id, :serial), id: 'serial') %>";
var nextDiv = $('#author_book').next();
if(nextDiv.hasClass('select2')) {
nextDiv.remove();
}
$('#author_book').remove();
$('#author').next().after(dropdown);
$('#author_book').select2();
haml文件如下所示:
#author
= simple_form_for :author, url: author_path(store_id: current_store), html: {method: 'post', remote: true, id: nil, class: 'none'} do |f|
#left-scheduled_publications-form
= f.input_field :authors, collection: authors, required: true
%br
= select_tag :author_book, options_for_select([], params[:author_book]), required: true
但是它破坏了我的家,而且真的很丑。 看来他们是一个相关问题,但也许我错了。
有什么更好的方法来解决这个问题? 是否可以更轻松地替换数据?
将您的第二个选择放在部分中:
_author_book.haml.erb
= select_tag :author_book, options_from_collection_for_select(@books, :id, :serial), id: 'serial')
在视图中添加一个包含div
的动态内容:
#author
= simple_form_for :author, url: author_path(store_id: current_store), html: {method: 'post', remote: true, id: nil, class: 'none'} do |f|
#left-scheduled_publications-form
= f.input_field :authors, collection: authors, required: true
.author-books
= select_tag :author_book, options_for_select([], params[:author_book]), required: true
在您的JS响应中:
$(".author-books").replaceWith("<%= escape_javascript(render: 'author_book') %>");
$('#author_book').select2();
理想情况下,您还希望在表单的初始呈现中包括不完整的部分,可以通过将@books
设置为空数组来实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.