Jquery - How to make $.post() use contentType=application/json?

Posted by JK on Stack Overflow See other posts from Stack Overflow or by JK
Published on 2010-05-16T21:01:28Z Indexed on 2010/05/16 21:10 UTC
Read the original article Hit count: 138

Filed under:
|
|

I've noticed that when using $.post() in jquery that the default contentType is application/x-www-form-urlencoded - when my asp.net mvc code needs to have contentType=application/json

(See this question for why I must use application/json: http://stackoverflow.com/questions/2792603/aspnet-mvc-why-is-modelstate-isvalid-false-the-x-field-is-required-when-that)

How can I make $.post() send contentType=application/json? I already have a large number of $.post() functions, so I don't want to change to $.ajax() because it would take too much time

If I try

$.post(url, data, function(), "json") 

It still has contentType=application/x-www-form-urlencoded. So what exactly does the "json" param do if it does not change the contenttype to json?

If I try

$.ajaxSetup({
  contentType: "application/json; charset=utf-8"
});

That works but affects every single $.get and $.post that I have and causes some to break.

So is there some way that I can change the behavior of $.post() to send contentType=application/json?

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about jquery-ajax