how to submit Form with AJAX Using enctype="multipart/form
如何使用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.
Edited to add:
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.
Here's a way that works even with IE8 and above:
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>
链接地址: http://www.djcxy.com/p/22198.html
上一篇: 什么是http multipart请求?