Select2 generating id with ajax response data

旧街凉风 提交于 2019-12-08 04:12:16

问题


My JSON response data does not contain an ID field, which is required by Select2 in order to display results. In the documentation they provide a way to generate id, however, I was unable to do so. Can someone provide an example on how to do this? I have tried this so far:

  $('.itemSearch').select2(
     ajax: {
     type: "POST",
     url: '/Default.aspx/TestMethod',
     data: function(params){
       var query={
           message:params.term
       }
       return JSON.stringify(query);
     },
     processResults: function (data) {
                var data1 = $.map(data, function (obj) {
                   obj.id = obj.id || obj.ItemNumber; // replace pk with your identifier
                   return obj;
                });                         
      return {
         results: data.items,
      };
    }
   }
 });

回答1:


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.



来源:https://stackoverflow.com/questions/47797831/select2-generating-id-with-ajax-response-data

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