简体   繁体   English

如何在select2中访问HTTP响应标头

[英]How to access HTTP response headers in select2

I am using the select2 to build select boxes with a lazy-appending result list . 我正在使用select2构建带有延迟添加结果列表的选择框。 However, the pagination data (eg the total item count) is not part of the JSON response. 但是,分页数据(例如,项目总数)不是JSON响应的一部分。 Hence, I am unable to access them in the ajax.results function. 因此,我无法在ajax.results函数中访问它们。 Instead, the pagination data is part of the HTTP response headers. 相反,分页数据是HTTP响应标头的一部分。

Is there some kind of interception mechanism build into select2's ajax so that I can access the HTTP headers and write them into the actual result data? select2的ajax中是否内置了某种拦截机制,以便我可以访问HTTP标头并将它们写到实际结果数据中?

@fynn's answer no longer works in Select2 4.x, here's an example that does. @fynn的答案不再适用于Select2 4.x,这是一个示例。

It checks for X-Page (current page number, eg "1") and X-Total-Pages (eg "5") headers. 它检查X-Page (当前页号,例如“ 1”)和X-Total-Pages (例如“ 5”)标题。 If those aren't present it also checks for a Link header with rel=next as at https://developer.github.com/v3/#pagination 如果不存在,它还会通过rel=next检查Link标头,如https://developer.github.com/v3/#pagination

$(".js-data-example-ajax").select2({
  ajax: {
    url: '/path/to/index.json',
    dataType: 'json',
    delay: 250,
    data: function (params) {
      // Returns the query params that should be passed to the server
      return {
        q: params.term, // search term
        page: params.page
      };
    },
    transport: function(params, success, failure) {
      // Custom transport lets us get pagination info stored in the headers.
      // Check for X-Page and X-Total-Pages, and alternatively for Link rel=next
      var read_headers = function(data, textStatus, jqXHR) {
        var more;
        var current_page = parseInt(jqXHR.getResponseHeader('X-Page')) || 0;
        var total_pages = parseInt(jqXHR.getResponseHeader('X-Total-Pages')) || 0;
        var link = jqXHR.getResponseHeader('Link') || '';
        if ((current_page < total_pages) || (link.search(/<([^>]+)>;\s*rel\s*=\s*['"]?next['"]?\s*(,|$)/i) > -1)) {
          more = true;
        }
        else {
          more = false;
        }
        return {
          results: data,
          pagination: {
            more: more
          }
        };
      };
      var $request = $.ajax(params);
      $request.then(read_headers).then(success);
      $request.fail(failure);
    },
    cache: true
  }
});

I just solved the issue by providing a custom transport function: 我只是通过提供自定义传输功能解决了该问题:

transport: function(params) {
    var callback = params.success;
    params.success = function(data, textStatus, jqXHR) {
        callback({
            items: data,
            total: jqXHR.getResponseHeader('HeaderName')
        }, textStatus, jqXHR);
    };
    return $.ajax(params);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM