如何使用AJAX使用enctype =“multipart / form-data”提交表单?
Short answer: you don't. You cannot upload files via AJAX.
The usual workaround is to set the target of your form to a hidden iframe
and submit the form there, using a normal, non-AJAXy POST, to achieve the desired effect:
<form target="hiddenIframe" method="post" enctype="multipart/form-data">
...
</form>
<iframe name="hiddenIframe" id="hiddenIframe" style="display: none;" />
There's a jQuery plugin that uses this technique.
XMLHttpRequest level 2 added support for uploading files via AJAX, and its browser support is now good and growing. Here's a browser support overview .
Use malsup's jquery form plugin , which will take care of both XHR as well as the hidden iframe that IE needs for ajax upload.
Code snippet here:
<form id="formid" action="" enctype="multipart/form-data" method="POST" accept-charset="utf-8">
.
.
.
</form>
<script type="text/javascript">
$(document).ready(function()
{
var options = {
cache:'false', //IE FIX
data: $('#formid').serialize(),
dataType: 'json',
processData: false,
contentType: false,
success: function(data)
{
//success action
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
//error action
}
};
$('#formid').ajaxForm(options);
});
</script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.