无法使用 ajax 填充 Select2 v4.x

Can't populate Select2 v4.x with ajax

我使用的是最新版本的 select2(第 4 版),我设法通过 AJAX 发出请求,并且我已经检查过响应是否正常。但是,select 没有使用在搜索中找到的结果填充其选项。也许我遗漏了什么但我不知道,这是代码:

<script type="text/javascript">
  $("#cliente").select2({
    //allowClear: true,
    ajax: {
      url: "<%= clientes_getclientes_path(format: 'json') %>",
      dataType: 'json',
      delay: 250,
      data: function (params) {
        return {
          q: params.term, // search term
          page: params.page
        };
      },
      processResults: function (data, params) {
        // parse the results into the format expected by Select2.
        // since we are using custom formatting functions we do not need to
        // alter the remote JSON data
        return {
          results: data.clientes
        };
      },
      cache: true
    },
    //escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
    minimumInputLength: 3,
    theme: 'bootstrap'
  });
</script>

您应该重命名您的 JSON,这样它将 return id 而不是 cod_ctetext 而不是 nom_cte,或者(效率较低),使用映射:

return {
  results: $.map(data.clientes, function (obj) { return { id: obj.cod_cte, text: obj.nom_cte };})
};