Or any other function to preprocess your data for that matter :)
Because of my server side framework, I always need to call JSON.stringify before sending my data - unnecessary boilerplate, that you can forget to add.
Right now I have:
$.ajax({ [...] data: JSON.stringify({ someData: self.someData }), [...] });
I would prefer:
$.ajax({ [...] data: { someData: self.someData }, [...] });
I've looked into ajaxSetup, but can't find a solution for this, so far...
Update
For a reason why I need this, see the following this question. I could fix this on the serverside, but for now I'm looking for a way to fix this on the clientside.
No, there is no built-in way to pre-process your data from an object to JSON. However, you can use ajaxSetup
and a beforeSend
to do it for you.
$.ajaxSetup({ beforeSend: function(jqXHR,options){ if ( options.contentType == "application/json" && typeof options.data != "string" ) { options.data = JSON.stringify(options.data); } } });
Now just make sure to set your contentType
to application/json
on requests that need to send json to the server so that it will get caught by the if statement.
Here an alternative approach that uses a jQuery.prefilter:
$.ajaxPrefilter("json", function(options, originalOptions) { options.data = JSON.stringify(originalOptions.data || null); options.contentType = "application/json" // content type of *request* }); $.ajax({ data: {foo: [1,2,3]}, dataType: "json" // expected content type of *response* (must match prefilter, above!) [...] });
Because prefilters match on the dataType
option, we have to set it manually in our $.ajax
request. If the dataType
matches the prefilter ("json") then before the request is sent, it will convert the data
object to a string, and set the contentType
header to match ("application/json").
Keep in mind that this a a global change that will impact ALL future $.ajax
requests with dataType: "json"
!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With