Javascript 如何使用 enctype="multipart/form-data" 使用 AJAX 提交表单?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5663207/
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-23 18:20:48  来源:igfitidea点击:

how to submit Form with AJAX Using enctype="multipart/form-data"?

javascripthtmlajax

提问by Sureshkumar Menon

how to submit Form with AJAX Using enctype="multipart/form-data"?

如何使用 enctype="multipart/form-data" 使用 AJAX 提交表单?

回答by Henning

Short answer: you don't. You cannot upload files via AJAX.

简短的回答:你没有。您无法通过 AJAX 上传文件。

The usual workaround is to set the target of your form to a hidden iframeand submit the form there, using a normal, non-AJAXy POST, to achieve the desired effect:

通常的解决方法是将表单的目标设置为隐藏iframe并在那里提交表单,使用普通的非 AJAXy POST,以达到预期的效果:

<form target="hiddenIframe" method="post" enctype="multipart/form-data">
    ...
</form>
<iframe name="hiddenIframe" id="hiddenIframe" style="display: none;" />

There's a jQuery pluginthat uses this technique.

有一个使用这种技术的jQuery 插件

Edited to add:

编辑添加:

XMLHttpRequest level 2added support for uploading files via AJAX, and its browser support is now good and growing. Here's a browser support overview.

XMLHttpRequest 级别 2增加了对通过 AJAX 上传文件的支持,它的浏览器支持现在很好并且还在增长。这是浏览器支持概述

回答by George

Here's a way that works even with IE8 and above:

这是一种甚至适用于 IE8 及更高版本的方法:

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.

使用malsup 的jquery 表单插件,它将处理XHR 以及IE 上传ajax 所需的隐藏iframe。

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>