Using the native XMLHttpRequest
object, it's possible to add an event listener to the onreadystatechange
event, and be notified when the readyState
is 2
, or HEADERS_RECEIVED
.
This is useful, as this enables the reading of the HTTP response headers before a long transfer is completed.
However in jQuery's AJAX wrapper, there doesn't seem to be any way to do this. The jQuery.ajax API documentation actually says the following.
No
onreadystatechange
mechanism is provided, however, sincedone
,fail
,always
, andstatusCode
cover all conceivable requirements.
Unless I'm mistaken, all of the listed callbacks are fired after the entire request is received, which may be a long time after the headers are available and readyState
is 2
.
Is there a way to add a callback to onreadystatechange
and/or readyState
2
when using jQuery's AJAX wrapper, without polling the readyState
property?
I suppose it would be possible to poll the readyState
property of the AJAX object using setInterval
, but I do not consider this to be a real solution for obvious reasons. I also do not consider modifying jQuery's core to be a real solution either.
Update:
Another SO user directed me to this question. Unfortunately, none of those answers seem to work. Modifying jQuery is not a real solution. Using jQuery to create a XHR object kind-of defeats the purpose. And the last answer doesn't work at all. In fact, the whole question looks to be for an outdated jQuery.
Well, the short answer is that jQuery does not provide this functionality due to compatibility issues in legacy browsers. To resolve the issues, jQuery simply lowers the bar to the lowest common denominator.
The slightly longer answer is it can be monkey patched into it, using the beforeSend
and xhr
methods, but this is not trivial, especially when you factor in legacy and cross-browser compatibility. To ease the pain, I've create a jQuery plugin that does just that.