fynn fynn - 2 days ago 3
jQuery Question

How to access HTTP response headers in select2

I am using the select2 to build select boxes with a lazy-appending result list. However, the pagination data (e.g. the total item count) is not part of the JSON response. Hence, I am unable to access them in the

ajax.results
function. Instead, the pagination data is part of the HTTP response headers.

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?

Answer

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);
}
Comments