【问题标题】:Unable to show "Searching" when using select2 (Loading remote data)使用 select2 时无法显示“正在搜索”(加载远程数据)
【发布时间】:2021-04-30 20:31:33
【问题描述】:

参考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>

以及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
    });

结果:

【问题讨论】:

  • search/products 肯定返回有效的json?
  • 是的,搜索结果显示正常
  • 我遇到了同样的问题。加载时,我在那里显示了一个“未定义”。如果你还记得你找到的解决方案,@tony.0919,那就太棒了!

标签: jquery-select2


【解决方案1】:
function formatRepo (repo) {
    if (repo.loading) return repo.text;

    var markup = '<div class="clearfix">' +
    '<div class="col-sm-1">' +
    '<img src="' + repo.owner.avatar_url + '" style="max-width: 100%" />' +
    '</div>' +
    '<div clas="col-sm-10">' +
    '<div class="clearfix">' +
    '<div class="col-sm-6">' + repo.full_name + '</div>' +
    '<div class="col-sm-3"><i class="fa fa-code-fork"></i> ' + repo.forks_count + '</div>' +
    '<div class="col-sm-2"><i class="fa fa-star"></i> ' + repo.stargazers_count + '</div>' +
    '</div>';

    if (repo.description) {
      markup += '<div>' + repo.description + '</div>';
    }

    markup += '</div></div>';

    return markup;
  }

  function formatRepoSelection (repo) {
    return repo.full_name || repo.text;
  }

  $ajax.select2({
    ajax: {
      url: "https://api.github.com/search/repositories",
      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, except to indicate that infinite
        // scrolling can be used
        params.page = params.page || 1;

        return {
          results: data.items,
          pagination: {
            more: (params.page * 30) < data.total_count
          }
        };
      },
      cache: true
    },
    escapeMarkup: function (markup) { return markup; },
    minimumInputLength: 1,
    templateResult: formatRepo,
    templateSelection: formatRepoSelection
  });

在选择 2 中加载存储库的完整代码您可以根据您的要求更改此代码

我的多选选择框

<select id="to_users" name="to_users" class="form-control js-data-example-ajax" multiple="multiple">
                                                        </select>

你可以格式化结果

processResults: function(data, page) {
                    // 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: $.map(data, function(obj) {
                        return { id: obj.user_id, text: obj.name };
                    })
                        //results: data
                    };
                },

如果您将结果格式化为 select2 行为,则禁用代码

/*  escapeMarkup: function(markup) {
                return markup;
            }, // let our custom formatter work

            templateResult: formatRepo, // omitted for brevity, see the source of this page
            templateSelection: formatRepoSelection // omitted for brevity, see the source of this page*/

【讨论】:

    【解决方案2】:

    请尝试

    function formatRepo(repo) {
      if (repo.value == undefined) {
        repo.value = 'Loading...'
      }
      var markup = '<div class="clearfix">' + repo.value + '</div>'
    
      return markup;
    }
    

    【讨论】:

      【解决方案3】:

      对于上述问题,有一个可能的解决方法。随意制作 cmets。

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

      var formatProduct = function(data){
         return '<div>'+(data.name)+'</div>';
      }
      

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

      var formatProduct = function(data){
         return '<div>'+(data.name || data.text)+'</div>';
      }
      

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

      this.template(data, option);
      

      this.template 指向 select2.js 第 1058 行

      Results.prototype.template = function (result, container) {
        var template = this.options.get('templateResult');
        container.innerHTML = template(result);
      };
      // result is an object indicating whether the data is loading.
      // {disabled: true, loading: true, text: "Searching…"}
      

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

      【讨论】:

        【解决方案4】:

        在我的例子中,它是 formatProduct 函数(它在我的代码中具有不同的名称,但它是同一个东西)。 假设您为 templateResult 调用 formatProduct:

        templateResult: formatProduct
        

        在这种情况下,您必须检查 formatProduct 返回的内容,例如:

        function formatProduct(product) {
                   return product.name || product.text;
                 }
        

        在我的情况下,我总是返回 product.name 并且“搜索”文本位于 product.text 下,因此我必须在尚未找到产品时检查以显示它。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-01-02
          • 2015-05-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多