尝试使用jQuery.ajax发送FormData时出错

时间:2016-12-30 12:08:28

标签: javascript jquery ajax multipartform-data

我有一个文件要发送到服务器。该文件在FormData对象中传递,而不是作为路径URI传递。这是我正在使用的代码:

let formData = new FormData();
formData.append('enctype', 'multipart/form-data');
formData.append('mode', 'fileInsert');
formData.append('conId', 'asdasd5535asf');
formData.append('user', 'user2422424');
formData.append('filesNumber', 1);
formData.append('msgType', 'fil');
formData.append('file0', file);

$.ajax({
    data: formData,
    success: function (a, s) {
        debugger;
    }
});

当代码到达$.ajax时,会抛出此错误:

  

未捕获的TypeError:非法调用

有什么问题?请注意,之前正在配置jQuery AJAX,包括帖子类型,URL等。

1 个答案:

答案 0 :(得分:3)

您需要在AJAX请求中设置以下属性:

contentType: false, 
processData: false

contentType设置为false会停止设置content-type标头。同样,将processData设置为false将停止正在编码的请求的内容,这在发送FormData对象时是必需的。

有关这些和其他$.ajax属性的详细信息,请参阅jQuery Documentation

相关问题