使用templateResult和Ajax

时间:2019-02-26 12:28:55

标签: jquery jquery-select2

我需要使用templateResult在带有ajax的select2上格式化结果。

<select id="example" style="width:400px">
<optgroup data-anag="Month" data-col1="Col1" data-col2="Col2">
    <option data-anag="January" data-col1="jan1" data-col2="jan2" value="JAN">January</option>
    <option data-anag="February" data-col1="feb1" data-col2="feb2" value="FEB">February</option>
    <option data-anag="March" data-col1="mar1" data-col2="mar2" value="MAR">March</option>
    <option data-anag="April" data-col1="apr1" data-col2="apr2" value="APR">April</option>
</optgroup>
</select>

<select id="example2" style="width:400px">
</select>




function formatRes(data) {

  var month = $(data.element).data('anag');
  var c1 = $(data.element).data('col1');
  var c2 = $(data.element).data('col2');

  var $result = $(
    '<div class="row">' +
    '<div class="col-md-4 col-xs-4">' + month + '</div>' +
    '<div class="col-md-2 col-xs-2">' + c1 + '</div>' +
    '<div class="col-md-2 col-xs-2">' + c2 + '</div>' +
    '</div>'
  );
  return $result;
}



// NON AJAX VERSION: WORK GREAT
$('#example').select2({
    templateResult: formatRes
});


//AJAX VERSION: DOESN'T WORK

var jsonresp = '[ {"id":"1", "name": "January", "col1":"jan1", "col2":"jan2"},  {"id":"2", "name": "February", "col1":"feb1", "col2":"feb2"}, {"id":"3", "name": "March", "col1":"mar1", "col2":"mar2"}, {"id":"4", "name": "April", "col1":"apr1", "col2":"apr2"}]';

$("#example2").select2({
templateResult: formatRes,
      ajax: {
        url: "/echo/json/",
        delay: 500,
        dataType: 'json',
    params: {contentType: "application/json"},
                data: function(term, page){             
                //Code for dummy ajax response
                    return {
                        json: jsonresp,
                        delay: 0
            };
                },
        processResults: function (data) {
            return {
                results: $.map(data, function (item) {

                    return {
                        text: item.name,
                        id: item.id,
                        col1: item.col1,
                        col2: item.col2
                    }
                })
            };
        }
      }
    });

我需要在小提琴中从示例(1)到示例(2)建立相同的结果:

https://jsfiddle.net/sdejLqkx/2/

但是将版本与ajax结合使用时,我不知道如何编辑它以获得与示例(1)相同的结果结构:

  1. 带有optgroup机箱
  2. 在ajax版本中使用templateResult

编辑:我有一些改进。现在,我在使用ajax的响应中获得了列,但是我不知道如何添加optgroup附件。 https://jsfiddle.net/sdejLqkx/3/

1 个答案:

答案 0 :(得分:1)

来自select2 documentation: 在processResults中返回包含children个元素的根对象。

https://jsfiddle.net/071p5af8/1/

    processResults: function(data) {
      return {
        results: [{
          name: "Month",
          col1: "Col1",
          col2: "Col2",
          children: $.map(data, function(item) {
            item.text = item.name;
            return item;
          })
        }]
      };
    }