Search code examples
jqueryasp.netajaxcontent-typepagemethods

$.ajaxSetup does not set content type for Get requests


Code 1

$.ajax({url:"1.aspx/HelloWorld",type:"GET",dataType:"json",contentType:"application/json"});

Request Response for Code1

Code 2

$.ajaxSetup({
   contentType: "application/json",
   dataType: "json"
});

$.get("1.aspx/HelloWorld","",$.noop,"json");

Request Response for Code 2

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 ?


Solution

  • 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.