【ECMAScript】ajax请求
普通表单,默认会带上cookie
$.ajax({
url: '/test/getUserInfo',
method: 'POST',
data: {'token': token},
success: function(response) {
console.log('Success:', response);
},
error: function(xhr, status, error) {
console.error('Error:', error);
}
});
文件表单
var userId = '123';
var files = $('#file').prop('files');
let formdata = new FormData();
formdata.append('file', files[0]);
formdata.append('userId', userId);
$.ajax({
url: "/test/uploadFile",
data: formdata,
method: "POST",
dataType:"json",
processData: false,
contentType: false,
success:function(data){
console.log(data);
},
error:function(data){
alert(data.message);
}
});
创建了Form对象上传文件,processData和contentType两个参数必须为false,否则报错 Uncaught TypeError:Illegal invocation
带cookie表单,不加 xhrFields 也可带上cookie,不是必须的
$.ajax({
url: '/test/getUserInfo',
method: 'POST',
data: {'token': token},
xhrFields: {
withCredentials: true
},
success: function(response) {
console.log('Success:', response);
},
error: function(xhr, status, error) {
console.error('Error:', error);
}
});
标签:function,console,请求,formdata,ajax,ECMAScript,error,data From: https://www.cnblogs.com/yangchongxing/p/18500063