【ECMAScript】ajax请求

【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);
    }
});

 

posted @ 2024-10-24 17:57  翠微  阅读(2)  评论(0编辑  收藏  举报