Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a jQuery Ajax fetch only headers and decide wether to get the content?

I'm making an Ajax script based on jQuery.ajax() and have come to a point where I should somehow check if the link I'm trying to load is a html page or something different like a SWF, image or Zip.

So I need to somehow check the content-type header and decide if I should get the content also (if it's html) or throw the ajax call away and do a window.location = theUrl. What I don't want is to get the entire file just to find out it's a 100MB Zip file.

Is there a way to 'pause' (or abort) the request while its still going and read just the headers? A HEAD call is not an option because this way I would have to make 2 requests to the server every time.

Maybe some sort of hack with setTimeout and low-level xhr functions?

Update 1: Tried to get the headers from xhr in setTimeout before the request finished but it doesn't seem to populate it until all of the data has been fetched.

Update 2: I hacked my way around the jquery's thing that binds itself to onreadystatechange:

var xhrr = new window.XMLHttpRequest();
$.ajaxSetup({
    xhr: function() { return xhrr }
});

...
$.ajax(....);

var theirfunc = xhrr.onreadystatechange;
xhrr.onreadystatechange = function() {
    console.log('xhr state: ', xhrr.readyState);
    theirfunc();
};

So this gave me states 1, 2, 3, 4 in order and I could get the content-type and abort successfully. I'm still investigating why it won't work when jQuery itself creates the XMLHttpRequest object. If I skip the ajaxSetup part and get var xhrr = $.ajax(...) then bind the same way it won't work. So how is my xhr any different than jQuerys? I see they do it like this:

function createStandardXHR() {
    try {
        return new window.XMLHttpRequest();
    } catch( e ) {}
}

So it shouldn't make a difference?

Update 3: Found it! jQuery 1.6 returns a fake xhr object with just a small number of the properties and onreadystatechange is not one of them.

like image 534
stormbreaker Avatar asked Nov 02 '25 00:11

stormbreaker


1 Answers

By using type HEAD, jQuery will not download the content, it will fetch only the headers.

You can then get them by name, by using getResponseHeader on the returned XHR object.

$.ajax({
    type: 'HEAD',
    url: 'http://example.com/api.php',
    complete: function(xhr) {
        var contentLength = xhr.getResponseHeader('Content-Length');
    }
});

You can also get a list of all the response headers with :

xhr.getAllResponseHeaders()
like image 109
Rayjax Avatar answered Nov 03 '25 18:11

Rayjax



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!