使用AJAX将JSON标记加载到Select2中

好的,所以我使用下面的代码来获取标签列表并将其加载到select2框中。 这些选项作为["test1","test2"] ,它应该是正确的格式,但我假设它们需要以某种方式在循环中处理

  //This part is meant to grab the options. I am using model ID 473 for testing $('#ticket_style_id').on("change", function(e) { var tag_list = $.ajax({ url: "/grab_options/", async: false }).responseText; //This part is meant to load the tag_list into a select2 box based on the //selection above $("#ticket_option_list").select2({ tags: [ tag_list ] }); }) 

在此处输入图像描述

有趣的是,如果我替换以下内容:

  $("#ticket_option_list").select2({ tags: ["test1","test2"] }); 

……一切都很好。

在此处输入图像描述

此控制器代码返回JSON:

 def grab_options style = Style.find(params[:id]) respond_to do |format| format.js { render json: style.option_list.to_json } end end 

我建议采用以下方法有两个原因:

1)它强制响应被解释为JSON(因为dataType: 'json'

2)它使用成功回调而不是使用async: false

 $('#ticket_style_id').on("change", function(e) { var tag_list = $.ajax({ url: "/grab_options/<%= 473 %>", dataType: 'json', success: function(response) { $("#ticket_option_list").select2({ tags: response }); } }); }); 

编辑:

话虽这么说,我相信Select2有一个内置的AJAX方法,你可以在他们的教程中看到。