使用select2时无法显示"正在搜索"(加载远程数据)

ton*_*919 5 jquery-select2

请参阅https://select2.github.io/examples.html,加载远程数据时会显示"搜索"文本.但是,我不知道为什么在我的案例中显示"未定义".

这是css文件.

<div class="col-sm-9">
  <select class="js-data-example-ajax form-control" style="width:100%;">
    <option value="select2/select2" selected="selected">select2/select2</option>
  </select>
</div>
Run Code Online (Sandbox Code Playgroud)

和ajax调用的设置

$(".js-data-example-ajax").select2({
      ajax: {
        url: "/search/products",
        dataType: 'json',
        delay: 250,
        data: function (params) {
          return {
            q: params.term,
            page: params.page
          };
        },
        processResults: function (data, page) {
          return {
            results: data.items
          };
        },
        cache: true
      },
      minimumInputLength: 1,
      templateResult: formatProduct, 
      templateSelection: formatProductSelection
    });
Run Code Online (Sandbox Code Playgroud)

结果:

在此输入图像描述

ton*_*919 0

对于上述问题有一个可能的解决方法。欢迎发表评论。

\n\n

这是我之前写的代码,假设返回 JSON 是{"items":[{"id":1,"name":"Product1"},{"id":2,"name":"Product2"}]}

\n\n
var formatProduct = function(data){\n   return \'<div>\'+(data.name)+\'</div>\';\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

我已将代码修改如下,并且“正在搜索...”文本再次显示:

\n\n
var formatProduct = function(data){\n   return \'<div>\'+(data.name || data.text)+\'</div>\';\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

select2.js第798行,远程加载数据时

\n\n
this.template(data, option);\n
Run Code Online (Sandbox Code Playgroud)\n\n

this.template 指向 select2.js第 1058 行

\n\n
Results.prototype.template = function (result, container) {\n  var template = this.options.get(\'templateResult\');\n  container.innerHTML = template(result);\n};\n// result is an object indicating whether the data is loading.\n// {disabled: true, loading: true, text: "Searching\xe2\x80\xa6"}\n
Run Code Online (Sandbox Code Playgroud)\n\n

这里的模板采用自定义参数“templateResult”并生成文本,因此自定义函数必须包含data.text,否则返回underfined

\n