It's not obvious why you might want to access HTTP Response headers, and it's even less obvious how to do so when you decide you need to. Here's how to do it (in jQuery, of course).
This example uses ajaxForm()
to turn a form into an Ajax submit and then look for response headers. The ajaxForm callbacks can be considered an extension of the native jQuery ajax callbacks.
$(document).ready(function() {
var ajaxSubmitOptions = {
// the normal success callback is not used
// success: function (responseText) {
// ...
// } ,
complete: function (xhrObj, status) {
if(status == "error") { // 500 server error?
alert("There was an error processing this request.");
} else {
if (xhrObj.getResponseHeader("X-My-Custom-Header") != "") {
alert("Intercepted special HTTP header...");
alert(xhrObj.getResponseHeader("X-My-Custom-Header"));
}
else {
// call the function you normally would have used in the "success" callback:
this._success(xhrObj.responseText);
}
}
} ,
_success: function (responseText) {
alert("Normal success callback...");
alert(responseText);
}
};
$('#myForm').ajaxForm(ajaxSubmitOptions);
})
A few things to note:
- We do not use the normal
success()
callback, since all it receives is for an argument is the response text. Only the more advancedcomplete()
function gives us what we need. - In this example, there is a custom header "X-My-Custom-Header" that the Javascript is looking for. You get to set this using your favorite server-side language.
I consider it a design flaw in the jQuery Ajax implementation that you cannot directly access the XMLHttpRequest
object from the success()
callback function.
So when might you want to do this? That's a very good question =) I've found it useful for making your rich client handle a response that the browser might normally handle, such as a redirect. Otherwise, it's still something I have to explore.