3

按照Select2 项目页面上的示例,当用户滚动到结果集的底部时,我试图提取更多记录。

<script>
  $(document).ready(function() {
    $('#style_full_name').select2({
        placeholder: "Please type in the make and model",
        minimumInputLength: 3,
        ajax: {
          url: "/list_styles",
          dataType: 'json',
          quietMillis: 100,
          data: function (term, page) { // page is the one-based page number tracked by Select2
            return {
                q: term, //search term
                page_limit: 10, // page size
                page: page, // page number
            };
          },
          results: function (data, page) {
            var more = (page * 10) < data.total; // whether or not there are more results available

            // notice we return the value of more so Select2 knows if more results can be loaded
            return {results: data.styles, more: more};
          }
        },
        formatResult: styleFormatResult, // omitted for brevity, see the source of this page
        dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
        escapeMarkup: function (m) { return m; } // we do not want to escape markup since we are displaying html in results
    });
    function styleFormatResult(style) {
      var markup = "<table class='style-result'><tr>";
      if (style.dimage_url !== undefined) {
          markup += "<td class='style-image'><img src='" + style.dimage_url + "'/></td>";
      }
      markup += "<td class='style-info'><div class='style-title'>" + style.full_name + "</div>";
      //if (movie.critics_consensus !== undefined) {
      //   markup += "<div class='movie-synopsis'>" + movie.critics_consensus + "</div>";
      //}
      //else if (movie.synopsis !== undefined) {
      //    markup += "<div class='movie-synopsis'>" + movie.synopsis + "</div>";
      //}
      markup += "</td></tr></table>"
      return markup;
    }
  });
</script>

在 Select2 的页面上测试 Rotten Tomatoes API 示例并在 Chrome 控制台中跟踪网络面板时,我可以看到到达滚动列表底部时触发了回调。当我在上面自己的用例中滚动到滚动列表的底部时,不会发生这种情况。

4

1 回答 1

3

经过一番挖掘后,我意识到问题是“总”不是我的 json 响应的一部分,因此var more = (page * 10) < data.total评估为假。这是使无限滚动工作所需的样式控制器 (RoR) 中的代码:

  def list_styles 
    #sunspot solr query
    @styles = Style.search { fulltext params[:q]; paginate :page => params[:page], :per_page => params[:page_limit] }

    #Build Json String
    @styles = "{\"total\":#{@styles.total}, \"styles\":#{@styles.results.to_json(:only=>[:id, :full_name], :methods => [:dimage_url, :dimage_url_medium])}}"

    #Render Json Response
    respond_to do |format|
      format.json {render :json => @styles }
    end
  end
于 2013-05-17T05:23:36.630 回答