Select2 generating id with ajax response data

时间秒杀一切 提交于 2019-12-06 21:46:33

Here is a correct snippet, using index in map function as id for Select2:

var data = [{
    "text": "Test item no. 1"
  },
  {
    "text": "Test item no. 2"
  },
  {
    "text": "Test item no. 3"
  },
  {
    "text": "Test item no. 4"
  }
];

$('.itemSearch').select2({
  ajax: {
    type: "POST",
    url: '/echo/json/',
    data: function(params) {
      var query = {
        message: params.term,
        data: data
      }
      return {
        json: JSON.stringify(query)
      }
    },
    processResults: function(data) {
      var data1 = $.map(data.data, function(obj, idx) {
        obj.id = obj.id || idx;
        return obj;
      });
      return {
        results: data1,
      };
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />

<select id="myselect2" class="itemSearch" data-placeholder="click to load..." style="width:200px">
</select>

A working fiddle is available here: https://jsfiddle.net/beaver71/7rqg3rck/


P.S.:

Code snippet here on SO does not work because there is an Ajax call.

On the contrary Jsfiddle enables users to simulate those Ajax calls, but in the example data are sent (via POST) to the "/echo/json/" service and reflected back as a result of the same Ajax request.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!