【问题标题】:Kendo get data from remote service, do paging locallyKendo 从远程服务获取数据,在本地进行分页
【发布时间】:2015-11-02 15:03:39
【问题描述】:

代码:

var url = base_url + "/api/v1/users/getUsers";
var dataSource = new kendo.data.DataSource({
  transport: {
    read: function (options) {
      $.ajax({
          type: 'GET',
          url:url,
          dataType: 'json',
          data: { searchTerm: $("#searchTerm").val().trim() },
          success: function (result) {
          options.success(result);
        },
        error: function (result) {            
          options.error(result);
        }
      });
    }
  },
  schema: {
    data: function (result) {
     return result.model;
    },
    total: function (result) {
      return result.model.length;
    },
  },
  pageSize: 5
});

$("#matches").kendoListView({
  dataSource: dataSource,
  autoBind: false, // if set to false the widget will not bind to the data source during initialization.
  template: kendo.template($("#matchesListViewTemplate").html())
});

$("#pager").kendoPager({
  dataSource: dataSource,
  autoBind: false
});

$(document).keypress(function (e) {
  if (e.which == 13) {
    e.preventDefault();      

    var searchTerm = $("#searchTerm").val().trim();
    if (searchTerm.length < 1)
      return;

    dataSource.read(); 
    dataSource.page(1); // makes another call to the remote service
  }
});

因为数据源是远程的,所以当我们调用 dataSource.page(1) 时,kendo 会再次调用远程服务。此行为在 so post 中进行了描述:

如果您正在执行服务器端分页,那么执行 grid.dataSource.page(1) 就足够了,因为这将完全按照您已经意识到的那样调用读取。

我必须进行哪些更改,以便在使用新的 searchTerm 进行搜索后,API 调用将只执行一次,并且寻呼机将转到第 1 页而无需再次调用?

我尝试使用 dataSource.query() 但仍然没有运气?我希望我表现得足够好。

【问题讨论】:

    标签: kendo-ui kendo-datasource


    【解决方案1】:

    解决方法是在dataSource.read()获取数据/完成时调用dataSource.page(1)。

    $(document).keypress(function (e) {
      if (e.which == 13) {
        e.preventDefault();      
    
        var searchTerm = $("#searchTerm").val().trim();
        if (searchTerm.length < 1)
          return;
    
        dataSource.read().done(function() {
    
          // in case remote service returns empty result set (but still http 200 code)
          // page() makes another request (if data() is empty it makes another request)
          // therefore we must check data length/total
          if( dataSource.total() > 0)
            dataSource.page(1);
        }
    });
    

    如果读取请求的响应尚未到达或发生错误,则允许另一个读取请求(以获取数据)。 DataSource.read() 发出异步请求,然后 dataSource.page(1) 开始执行。 DataSource.page(1) 函数检查是否有任何数据读取,如果没有,它会再次执行 read 方法 - 因此我们得到了 2 个调用,正如你提到的那样。因为异步调用可能会发生这种情况。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-25
      • 1970-01-01
      • 2020-07-20
      • 2017-08-14
      • 1970-01-01
      • 1970-01-01
      • 2020-10-28
      • 2012-05-04
      相关资源
      最近更新 更多