Pass accepts header parameter to jQuery AJAX
Try this ,
$.ajax({
headers: {
Accept: "text/plain; charset=utf-8",
"Content-Type": "text/plain; charset=utf-8"
}
data: "data",
success : function(response) {
// ...
}
});
See this post for reference:
Cannot properly set the Accept HTTP header with jQuery
There two alternate ways to set accept header, which are as below:
1) setRequestHeader('Accept','application/json; charset=utf-8');
2) $.ajax({
dataType: ($.browser.msie) ? "text" : "json",
accepts: {
text: "application/json"
}
});
In recent versions of jQuery, setting "dataType" to an appropriate value also sets the accepts header. For instance, dataType: "json"
sets the accept header to Accept: application/json, text/javascript, */*; q=0.01
.
The other answers do not answer the actual question, but rather provide workarounds which is a shame because it literally takes 10 seconds to figure out what the correct syntax for accepts
parameter.
The accepts
parameter takes an object which maps the dataType
to the Accept
header. In your case you don't need to even need to pass the accepts
object, as setting the data type to json
should be sufficient. However if you do want to configure a custom Accept
header this is what you do:
accepts: {"*": "my custom mime type" },
How do I know? Open jquery's source code and search for "accepts". The very first find tells you all you need to know:
accepts: {
"*": allTypes,
text: "text/plain",
html: "text/html",
xml: "application/xml, text/xml",
json: "application/json, text/javascript"
},
As you see the are default mappings to text
, html
, xml
and json
data types.
Try this:
$.ajax({
beforeSend: function (xhr){
xhr.setRequestHeader("Content-Type","application/json");
xhr.setRequestHeader("Accept","text/json");
},
type: "POST",
//........
});