Skip to content

Instantly share code, notes, and snippets.

@pithyless
Created January 1, 2012 14:02
Show Gist options
  • Save pithyless/1547408 to your computer and use it in GitHub Desktop.
Save pithyless/1547408 to your computer and use it in GitHub Desktop.
jQuery set Headers for $.ajax
// jQuery Headers support for $.ajax
$.ajax({
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Accept","application/json");
}
type: "POST",
url: "/article",
processData: false,
data: jsonData,
dataType: "json",
success: function(json){
do something...
}
});
@pithyless
Copy link
Author

Cannot properly set the Accept HTTP header with jQuery
http://stackoverflow.com/questions/1145588/cannot-properly-set-the-accept-http-header-with-jquery

beforeSend: function(req) {
        req.setRequestHeader("Accept", "text/xml");
    },

Answer:

I also had trouble with this, not just in IE but also in Chrome and Safari using jQuery 1.6.2. This solution appears to work as intended in all browsers I've tried (Chrome, Safari, IE, Firefox).

$.ajax({
    headers: { 
        Accept : "text/plain; charset=utf-8",
        "Content-Type": "text/plain; charset=utf-8"
    }
    data: "data",
    success : function(response) {
        ...
    }
})

@molokoloco
Copy link

For me it work like this :)

apiReq = $.ajax({
    url        : APP.apiUrl + path,
    method     : method || 'get',
    //cache    : false,
    crossDomain: true,
    contentType: contentType || 'application/json',
    dataType   : 'json',
    processData: false,
    data       : values || null,
    success    : success || APP.onSuccess,
    error      : error || APP.apiError
});

@lazaropj
Copy link

I'm trying this:

$.ajax({
headers: {
Accept : "text/javascript; charset=utf-8",
"Content-Type": "text/javascript; charset=utf-8"
},
type: "GET", url: rootURL, dataType: "jsonp",
beforeSend: function(xhr){
xhr.setRequestHeader('Access-Control-Allow-origin', 'true');
},
//jsonp: false,
//jsonpCallback: 'eval',
success: function(data) {
console.log(data);
},
error: function(jqXHR, msg, erro){
console.log(erro);
}
});

But the request is going:

Accept: /

HELP!!

@nakechai
Copy link

nakechai commented Apr 5, 2018

hello i think only the server can set 'Access-Control-Allow-origin' @lazaropj

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment