传递给jquery ajax的标头参数
当我在Chrome控制台中检查以下代码时,它向我显示了请求标头beforeSend
jQuery.ajax({
url: _this.attr('href'),
accepts: "application/json; charset=utf-8",
});
});
如何将接受类型设置为json。 我不想设置自定义标题或使用beforeSend
8个解决方案
58 votes
尝试这个 ,
$.ajax({
headers: {
Accept: "text/plain; charset=utf-8",
"Content-Type": "text/plain; charset=utf-8"
}
data: "data",
success : function(response) {
// ...
}
});
请参阅此帖子以供参考:
无法使用jQuery正确设置Accept HTTP标头
karthick answered 2019-12-26T22:11:15Z
34 votes
设置接受标头有两种方法,如下所示:
1) setRequestHeader('Accept','application/json; charset=utf-8');
2) $.ajax({
dataType: ($.browser.msie) ? "text" : "json",
accepts: {
text: "application/json"
}
});
gaurang171 answered 2019-12-26T22:11:34Z
16 votes
在最新版本的jQuery中,将“ dataType”设置为适当的值也会设置accepts标头。 例如,dataType: "json"将accept标头设置为Accept: application/json, text/javascript, */*; q=0.01。
koppor answered 2019-12-26T22:11:55Z
11 votes
其他答案没有回答实际问题,而是提供了变通方法,这很可惜,因为从字面上看需要10秒才能找出text参数的正确语法。
text参数采用一个对象,该对象将html映射到xml标头。 在您的情况下,您甚至不需要传递26753054334428129129对象,因为将数据类型设置为json就足够了。 但是,如果您确实想配置自定义Accept标头,请执行以下操作:
text
我怎么知道? 打开jquery的源代码并搜索“ accepts”。 最初的发现会告诉您所有您需要了解的内容:
accepts: {
"*": allTypes,
text: "text/plain",
html: "text/html",
xml: "application/xml, text/xml",
json: "application/json, text/javascript"
},
如您所见,它们是对text、html、xml和json数据类型的默认映射。
Roman Royter answered 2019-12-26T22:12:33Z
5 votes
尝试这个:
$.ajax({
beforeSend: function (xhr){
xhr.setRequestHeader("Content-Type","application/json");
xhr.setRequestHeader("Accept","text/json");
},
type: "POST",
//........
});
Srinivas answered 2019-12-26T22:12:53Z
5 votes
尽管其中一些是正确的,但我发现先前的回答很令人困惑。 同时,OP要求解决方案而不设置自定义标题或使用accepts,因此我一直在寻找更清晰的解释。 我希望我的结论对其他人有启发。
代码
jQuery.ajax({
....
accepts: "application/json; charset=utf-8",
....
});
不起作用,因为根据jQuery doc([http://api.jquery.com/jquery.ajax/),accepts必须为PlainObject(而不是String)。)特别地,jQuery期望零个或多个键值对 将每个dataType与它们接受的MIME类型相关联。 所以我最终使用的是:
jQuery.ajax({
....
dataType: 'json',
accepts: {
json: 'application/json'
},
....
});
Googol answered 2019-12-26T22:13:23Z
4 votes
您已经将accepts参数标识为所需参数,并且keyur正确显示了正确的设置方法,但是如果将DataType设置为“ json”,它将自动将accepts的默认值设置为所需的值 按照jQuery参考。 因此,您需要做的是:
jQuery.ajax({
url: _this.attr('href'),
dataType: "json"
});
Nathan Phillips answered 2019-12-26T22:13:43Z
2 votes
我用jQuery.getJSON( url [, data ] [, success( data, textStatus, jqXHR ) ] )例如:
var url="my.php";
$.getJSON( url, myObj )
.done(function( json ) { ... }) /* got JSON from server */
.fail(function( jqxhr, textStatus, error ) {
var err = textStatus + ", " + error;
console.log( "Failed to obtain JSON data from server: " + err );
}); /* failed to get JSON */
getJSON是以下内容的简写:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
iainH answered 2019-12-26T22:14:07Z