0

我想在select2中预填充数据

这是来自服务器的响应

https://jsfiddle.net/j6tv52s6/

我怎样才能对选择进行预填充?

在此处输入图像描述

这是我的 [小提琴][2]

这是HTML

<input type="hidden" name='zipcode_covered' id='zipcodeCollection' value="">
<select class="js-data-example-ajax" style="width:100%" multiple="multiple" placeholder='Pincode'></select>

这是脚本:

function formatRepo(repo) {
  if (repo.loading) return repo.text;
  var markup = '<div class="clearfix">' +
               '<div clas="col-sm-10">' +
               '<div class="clearfix">' +
               '<div class="col-sm-6">' + repo.zipcode + '</div>' +
               '</div>'
  markup += '</div></div>';
  return markup;
}

function formatRepoSelection(repo) {
  var cur_val = $('#zipcodeCollection').val();
  if (cur_val) {
    $('#zipcodeCollection').val(cur_val + "," + repo.zipcode);
  } else {
    $('#zipcodeCollection').val(repo.zipcode);
  } 
  return repo.zipcode;
}

$(document).ready(function(){
  $(".js-data-example-ajax").select2({
    ajax: {
      url: "getZipList",
      type: "POST",
      contentType: "application/json; charset=utf-8",
      delay: 250,
      data: function(params) {
        return {
          q: params.term, // search term
          page: params.page
        };
      },
      processResults: function (data, page) {
        return {
          results: data.items
        };
      },
      cache: true
    },
    escapeMarkup: function(markup) { return markup; }, // let our custom formatter work
    minimumInputLength: 1,
    templateResult: formatRepo, // omitted for brevity, see the source of this page
    templateSelection: formatRepoSelection // omitted for brevity, see the source of this page  
  });
});
4

1 回答 1

0

如果我理解你的问题是正确的.. 你想用来自服务器的选项填充一个选择下拉列表?

以下是使用 ajax 的方法:

 $.ajax({
        type: "POST",
        url: ajaxUrl,
        dataType: "json",
        success: function (domain) {
            $.each(domain.ZipCodes, function (index, value) {
                    $("#zipcodeDropdown").append(
                        $("<option></option>").text(value.zipCode).val(value.zipId)
                    );
            });
        },
        error: function (event) {
            ShowErrorLabel("ERROR in ajax call(" + ajaxUrl + "): \n" + "Error : " + event.status + " - " + event.statusText);
        }
    });
于 2016-03-03T18:13:04.690 回答