jQuery 如何使用jquery提交多部分表单数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39716481/
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
How to submit multipart formdata using jquery
提问by user3655266
<form id="uploadForm" enctype="multipart/form-data" action="http://localhost:1337/ad/upload" method="post" name="uploadForm" novalidate>
<input type="file" name="userPhoto" id="userPhoto" />
<input type="submit" value="submit" id="uploadImage" />
</form>
This is my html form which accepts an image as file inout, the user can select an image file and then click submit. This works but the url of the current page changes to localhost:1337/ad/upload. I want the page to stay at the same url.
这是我的 html 表单,它接受图像作为文件输入,用户可以选择一个图像文件,然后单击提交。这有效,但当前页面的 url 更改为 localhost:1337/ad/upload。我希望页面保持在相同的网址。
$("form#uploadForm").submit(function(event) {
event.preventDefault();
var formData = new FormData($(this)[0]);
var posting = $.post(url, formData);
})
I have tried this to send the form using jquery but i get an error : Uncaught Type error : Illegal Invocation
我已经尝试使用 jquery 发送表单,但出现错误:未捕获类型错误:非法调用
What data does the form submit when the type is multipart /formdata and how can we get this data on jQuery
当类型为 multipart /formdata 时表单提交什么数据,我们如何在 jQuery 上获取这些数据
回答by Developer
processData
处理数据
By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.
默认情况下,作为对象传递给 data 选项的数据(从技术上讲,除了字符串之外的任何内容)将被处理并转换为查询字符串,适合默认的内容类型“application/x-www-form-urlencoded” . 如果要发送 DOMDocument 或其他未处理的数据,请将此选项设置为 false。
Please check jQuery Ajax Documentation
Try ajax like this -
像这样尝试 ajax -
var form = new FormData($("#uploadForm")[0]);
$.ajax({
url: your_url,
method: "POST",
dataType: 'json',
data: form,
processData: false,
contentType: false,
success: function(result){},
error: function(er){}
});
回答by Rahul Patel
You can give to the formData all form for processing
您可以将所有表单交给 formData 进行处理
var form = $('#uploadForm')[0];
// You need to use standart javascript object here
var formData = new FormData(form);
or specify exact data for formdata
或为 formdata 指定确切的数据
var formData = new FormData();
formData.append('userPhoto', $('input[type=file]')[0].files[0]);