Loading JSON tags in Select2 using AJAX

Ok, so I use the code below to grab a list of tags and load it into select2 field. The parameters are returned as ["test1","test2"] , which should be of the correct format, but I assume that they should be processed in a loop somehow.

  //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/<%= 473 %>", 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 ] }); }) 

enter image description here

I wonder if you substitute the following:

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

... everything generates a fine.

enter image description here

JSON is returned by this controller code:

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

I would suggest the following approach for two reasons:

1) It forces the response to be interpreted as JSON (due to dataType: 'json' )

2) It uses a success callback instead of using 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 }); } }); }); 

EDIT:

I believe that Select2 has a built-in AJAX method, which you can see in your tutorial .

+3
source

Source: https://habr.com/ru/post/1238908/


All Articles