jQuery.ajax() 设置 Headers 中的 Accept 内容

时间:2023-03-09 07:49:19
jQuery.ajax() 设置 Headers 中的 Accept 内容

jQuery.ajax() 如何设置 Headers 中的 Accept 内容

其实很简单,首先如果是常见类型,则请直接设置 dataType 属性

$.ajax({
dataType: "json",
type: "get",
success: function (data) {
}
});

设置 dataType 后,会去 accepts 属性(此属性会预置一些常用类型)中直接拿相应的类型添加到 Accept 中。

jQuery.ajax() 设置 Headers 中的 Accept 内容

如果想自己自定义 jQuery 中没有的 Accept 内容,可以手动设置 accepts 属性,使用 键值对 存储,然后再设置 dataType 属性为刚刚自定义的键。

$.ajax({
accepts: {
xxx: "application/xxx"
},
dataType: "xxx",
type: "get",
success: function (data) {
}
});

当然还可以直接设置 headers 属性,直接写 Accept 的内容是什么。

$.ajax({
headers: {
Accept: "application/json; charset=utf-8"
},
type: "get",
success: function (data) {
}
});