$.ajax设置Content-Type
默认get方法没有Content-Type,post方法的Content-Type为:application/x-www-form-urlencoded; charset=UTF-8
手动设置
$.ajax({
type: 'post',
url:'/contentType',
contentType:'application/x-www-form-urlencoded',//手动设置
data:{
username:'admin',
password:'123123'
},//data可以是对象,使用contentType: “application/json”则data只能是json字符串
dataType:'json',
success:function (data) {
}
})
传递formData类型数据
//关键是设置:processData 和 contentType
//在使用jQuery的$.ajax()方法的时候参数processData默认为true(该方法为jQuery独有的)默认情况下会将发送的数据序列化以适应默认的内容类型application/x-www-form-urlencoded
var formData = new FormData();
var name = $("input").val();
formData.append("file",$("#upload")[0].files[0]);
formData.append("name",name);
$.ajax({
url : Url,
type : 'POST',
data : formData,
// 告诉jQuery不要去处理发送的数据,用于对data参数进行序列化处理 这里必须false
processData : false,
// 告诉jQuery不要去设置Content-Type请求头
contentType : false, //必须
})
axios设置content-ype
1、默认的transformRequest 会判断是否传入了Content-Type如果没有传入就根据数据类型自行设置
//default.transformRequest
if (utils.isURLSearchParams(data)) {
setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');
return data.toString();
}
if (utils.isObject(data)) {
setContentTypeIfUnset(headers, 'application/json;charset=utf-8');
return JSON.stringify(data);
}
//setContentTypeIfUnset
function setContentTypeIfUnset(headers, value) {
if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {
headers['Content-Type'] = value;
}
}
2、formData类型的数据会删除传入的Content-Type,由浏览器自行设置
if (utils.isFormData(requestData)) {
delete requestHeaders['Content-Type']; // Let the browser set it
}
Content-Type | transformRequest | post-urlsearch | post-object | post-formData |
---|---|---|---|---|
无 | 无 | application/x-www-form-urlencoded;charset=utf-8; | application/json;charset=utf-8; | multipart/form-data; boundary=----WebKitFormBoundaryBaQVpNmusAaiwJJy |
无 | 传入 | application/x-www-form-urlencoded; | application/x-www-form-urlencoded; | multipart/form-data; boundary=----WebKitFormBoundaryBaQVpNmusAaiwJJy |
传入 | 无 | 传入的值 | 传入的值 | multipart/form-data; boundary=----WebKitFormBoundaryBaQVpNmusAaiwJJy |
传入 | 传入 | 传入的值 | 传入的值 | multipart/form-data; boundary=----WebKitFormBoundaryBaQVpNmusAaiwJJy |
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。