将select2下拉列表的内容替换为ajax调用中的数据

Replace content of select2 dropdown with data from ajax call

本文关键字:调用 ajax 数据 select2 下拉列表 替换      更新时间:2023-09-26

我有一个带有两个下拉菜单的rails应用程序。当第一个选择为"author"时,它会调用ajax来检索author的书。自动电话簿。

在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设置为空数组来实现这一点。