$.ajaxSetup does not set content type for Get requests
Question by Deeptechtons
Code 1
$.ajax({url:"1.aspx/HelloWorld",type:"GET",dataType:"json",contentType:"application/json"});
Code 2
$.ajaxSetup({
contentType: "application/json",
dataType: "json"
});
$.get("1.aspx/HelloWorld","",$.noop,"json");
Code1 effectively sets both the content-type
and datatype
Code2 does not set the content-type Is this Intended or Have i to do Voodoo stuff for making it work ?
Answer by Kevin B
I would just create a quick wrapper for the ajax method.
$.myAjax = function(url,data){
return $.ajax({
contentType: "application/json",
url: url,
data: data || {},
type: "GET",
dataType: "json"
});
}
// used with
$.myAjax("foobar.asp").done(function(data){
console.log(data);
}).fail(function(){
console.log(arguments);
});
The reason that the header isn’t getting passed is that if the contentType isn’t specified for the given request and there is no data, the contentType is not set. It may be a bug since the contentType was set in the ajaxSetup, but I’m not positive on that.
Answer by Starx
$.ajaxSetup
hold the default options for most of the all ajax request, but does not send an ajax request it self.
But $.ajax
is the actual function that sends the request.
On Code 1:
It simply sends a GET Ajax request with comprehensive method $.ajax()
On Code 2:
The default options for all the ajax request are set before any request are sent. Then when the actual request is made using $.get, this parameters no longer have to be defined.
Update
This seems to be a bug. Such problem occurs when you are sending $.get
request without any data. Check here. You need to see the request headers using firebug or similar.