jQuery 通过 ajax 发送 FormData 对象和附加参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36448724/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:05:41  来源:igfitidea点击:

Send FormData object AND an additional parameter via ajax

jqueryjsonajaxform-data

提问by iuliu.net

I have managed to send a FormData object like so:

我已经设法发送一个 FormData 对象,如下所示:

var formData = new FormData();
formData.append('file', this.files[0]);
$.ajax({
   url: urlUploadProductsFile,
   type: 'POST',
   data: formData,
   cache: false,
   contentType: false,
   processData: false
}, 'json');

Now what I want to do is add an additional CustomerIdto send to the server. The following won't work:

现在我想要做的是添加一个额外CustomerId的发送到服务器。以下将不起作用:

var formData = new FormData();
formData.append('file', this.files[0]);
$.ajax({
   url: urlUploadProductsFile,
   type: 'POST',
   data: { "file": formData, "CustomerId": 2 },
   cache: false,
   contentType: false,
   processData: false
}, 'json');

And I also tried the following variations:

我还尝试了以下变体:

data: { "file": formData, "CustomerId": 2 }, processData: true

data: { "file": formData, "CustomerId": 2 }, processData: true

data: JSON.stringify({ "file": formData, "CustomerId": 2 })

data: JSON.stringify({ "file": formData, "CustomerId": 2 })

data: { "file": JSON.stringify(formData), "CustomerId": 2 }

data: { "file": JSON.stringify(formData), "CustomerId": 2 }

data: { file: formData, CustomerId: 2 }

data: { file: formData, CustomerId: 2 }

Any help appreciated.

任何帮助表示赞赏。

回答by Borik Bobrujskov

Try:

尝试:

var formData = new FormData();
formData.append('file', this.files[0]);
formData.append('CustomerId', 2);

/*
 note:: appending in form Data will give "csrf token mismatch error". 
 so better you make a input feild of type hidden with name = CustomerId 
 and value =  2 
*/ 

$.ajax({
   url: urlUploadProductsFile,
   type: 'POST',
   data: formData,
   cache: false,
   contentType: false,
   processData: false
}, 'json');

回答by Jiri Tousek

You need to either add it directly to formData(just as you did with 'file'), or alternatively use query (GET) parameters.

您需要将其直接添加到formData(就像您对 所做的那样'file'),或者使用查询 (GET) 参数。