在主干提取完成后获取响应标头

Get response headers after backbone fetch is complete

本文关键字:获取 响应 提取      更新时间:2024-03-30

我需要读取backbone.js fetch方法发出的Ajax请求中的响应标头。如果我重写fetch方法,有什么方法可以读取头吗:

var PageCollection = Backbone.Collection.extend({
    url: 'http://localhost/cms?_mn=Mod_Admin&_mf=getAllPages',
    model: PageModel,
    fetch: function (options) {
        Backbone.Collection.prototype.fetch.call(this, options);
        // The above line of code works and fetch the dataset 
        // BUT how i can read the response headers at this point
    }
});

使用"success"回调来获取xhr对象,因此您将能够获取所有响应标头:

collection.fetch({
    success: function (collection, response, options) {
        options.xhr.getAllResponseHeaders(); // To get all the headers
        options.xhr.getResponseHeader('header_name'); // To get just one needed header
    }
});

Backbone fetch()方法返回一个jqXHR对象。您可以对此对象调用done()来添加回调,该回调将在请求完成时调用。然后在同一个jqXHR对象上使用getResponseHeader()方法来获取您感兴趣的标头的值,或者调用getAllResponseHeaders()来获取所有标头。

因此,在fetch()方法的覆盖中,您可以执行以下操作:

var jqXHR = Backbone.Collection.prototype.fetch.call(this, options);
jqXHR.done(function() {
    // Get all headers:
    console.log('All headers:', jqXHR.getAllResponseHeaders());
    // Or get a specific header:
    console.log('Content-Length:', jqXHR.getResponseHeader('Content-Length'));
});

看看我的实现以及我如何使用解析函数

var CustomPageCollection = Backbone.Collection.extend({
    model: CustomPage,
    url: '/pb/editor/pages',
    parse: function(resp, xhr) {
        this.paginationInfo = JSON.parse(xhr.getResponseHeader('X-Pagination-Info'));
        return resp.items;
    }
});

我找到了一个更好的方法:当从服务器返回时,集合会激发一个"parse"函数BakcboneJs-集合分析

parse:function(a,b,c){      
    console.log("a",a);
    console.log("b",b);
    console.log("c",c);
},

我们的好友在b:)