使用AJAX将JSON标签加载到Select2中 [英] Loading JSON Tags into Select2 with AJAX

查看:125
本文介绍了使用AJAX将JSON标签加载到Select2中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Ok, so I am using the code below to grab a list of tags and load it up into a select2 box. The options are being returned as ["test1","test2"] which should be the correct format, but I am assuming they need to 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 ]
      });
  })

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

Interestingly if I substitute the following:

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

...一切都会好起来的.

...everything generates fine.

此控制器代码返回JSON:

The JSON is being 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

推荐答案

出于以下两个原因,我建议采用以下方法:

I would suggest the following approach for 2 reasons:

1)强制将响应解释为JSON(由于dataType: 'json')

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

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

2) It uses the 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
      });    
    }
  });
});

话虽如此,我相信Select2具有内置的AJAX方法,您可以在他们的教程.

That being said, I believe Select2 has a built in AJAX method that you can see in their tutorial.

这篇关于使用AJAX将JSON标签加载到Select2中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆