[jQuery] Headers support for $.ajax
This is a follow up to http://groups.google.com/group/jquery-en/browse_frm/thread/fcbb53bd33b30f96/6363fa2f4b444823
but since that post is over a year old comments are closed.
I have been looking at some RPC and REST systems lately and they all
recommend using the HTTP ACCEPT header. I would love to be using
jQuery with these, but am unable to get the full benefit without
support in $.ajax to set the header. i.e. to conform to
http://json-rpc.org/wd/JSON-RPC-1-1-WD-20060807.html would require:
$.ajax({
headers: {
"Content-Type": "application/json",
// could use contentType for the above but setting it this way to
illustrate the example
"Accept": "application/json"
},
type: "POST",
url: "/JSON-RPC",
processData: false,
data: jsonData,
dataType: "json",
success: function(json){
do something...
}
});
In a brief bit of research I have seen a few places that state headers
are not reliable in all browsers, but if that was resolved I would go
as far as to say the headers could even be automatically set for the
predefined values of dataType.
-wade
p.s. The original post outlined exactly where a change would be needed
to support this.
p.p.s
Just before I clicked the Post button on this one I took one more look
at the API docs and noticed "Use this to set custom headers" under
beforeSend. So, ok this CAN be done in $.ajax as it stands, but it is
not obvious. The above example would like like this:
$.ajax({
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("Content-Type","application/json");
// could use contentType for the above but setting it this way to
illustrate the example
xhrObj.setRequestHeader("Accept","application/json");
}
type: "POST",
url: "/JSON-RPC",
processData: false,
data: jsonData,
dataType: "json",
success: function(json){
do something...
}
});
I am going to post this anyways just for anyone else that searches the
forums looking for the same thing in the future.