select2 中的 processResult 不起作用

the processResult in select2 do not working

我使用 select2 加载远程数据 我发送 ajax 请求并正确获得响应,但 processResult 没有 运行 并且不会显示任何内容

javascript 代码:

var formatProduct= 
function(product) {
    console.log("formatProduct");
    if (product.loading) return product.text;
    var markup =  '<div class="product-to-compare" data=' + product.id + '>' + product.name + '</div>' ;
    return markup;
  }
var formatProductSelection = 
function (product) {
console.log("formatProductSelection");
return product.name || product.text;
}
$(".js-data-example-ajax").select2({
    placeholder: "Search for product",
    minimumInputLength: 2,
    ajax: {
        url: '/product/ajax_product_list/',
        dataType: 'json',
        quietMillis: 300,
        data: function (params) {
            var id = $('#product-no-1').attr('data') ;
            return {
                key: params,
                id: id
            };
        },
        processResults: function (data) {
        return {
            results: data.items
        };     
    },
    cache: true
  },
  escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  minimumInputLength: 1,
  templateResult: formatProduct, // omitted for brevity, see the source of this page
  templateSelection: formatProductSelection // omitted for brevity, see the source of this page
});    

和我的控制器 return 作为响应的 JSON :

{
"items": [
  {"id": "55dd980c8242b630cfaf4788", "name": "sallll"},
  {"id": "55d58d7a8242b62c6b88504e", "name" : "inja"}, 
  {"id": "55d58d558242b62c6b88504d", "name": "salam"}
  ]
}

您应该将 JSON 重命名为 return text 而不是 name

请注意,如果您使用的是旧版本的 select2 (<4),则应使用 results 而不是 processResults

processResults: function (data) {
  //There is my solution.Just directly manipulate the data
  $.each(data.items, function(i, d) {
    data.items[i]['text'] = d.name;
  });
  return {
      results: data.items
  };
}

在我的例子中,我正在刷新页面并查找为获取搜索数据而发送的 http 请求。因此,请务必搜索 processResult 接到电话。

在您的 JSON 数据中,您将 name 重命名为 text。因为select2数据只接受列名idtext.