Hello all, Please consider the following snippet of code, which transparently intercepts all Ajax requests, detects whether the data being POSTed is a JSON object, and based on that, switches the content type to "application/json", and serializes the data to a string:
$(document).ready(function() { $._ajax = $.ajax; $.ajax = function(s) { if (s.data && s.type == 'POST') { if (typeof s.data == 'object') { JSON.stringify(s.data); s.contentType = 'application/json'; } } return $._ajax(s); }; }); What I'm trying to figure out is how to achieve this (properly) without having to overwrite a core jQuery method, or if indeed there is a way. In an effort to save everyone time, here are the Wrong Answers: (1) Write my own custom method. This is wrong, because it breaks the inheritance pretty much every Ajax-related method jQuery has. The goal of this exercise should be associated with words like "seamless" and "transparent". This isn't. (2) Use beforeSend(). This does not work, because the Content-Type header has already been set, and amazingly, the XHR object offers no facility for removing or replacing headers, only appending. (3) Use $.ajaxSetup, and set contentType: "application/json" across the board. This simply reverses the problem by requiring me to specify contentType any time I *don't* want to use JSON in an Ajax request. Incidentally, this also breaks $.post, since it provides no way to specify the contentType (which I suppose would normally be redundant anyway). (4) Use ajaxStart(). Again, not an option, since it is global (which means any requests fired off in parallel will result in at least one not being intercepted). Also, it doesn't have access to the XHR object, which puts a bit of a damper on things. If a solution within the required parameters does not exist, is this something that people have run into before? Would it be worth kicking up the chain? Handling JSON data transparently seems like an obvious thing to want to do, and thus far I've been a little taken aback at how many issues I've run into. Thanks for your time and consideration.