如何使用javascript清除/重置formData()? [英] How to Clear/Reset formData() using javascript?

查看:2272
本文介绍了如何使用javascript清除/重置formData()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用formData进行Ajax Image Uploading,当我第一次提交它会成功上传时,再次点击发布到服务器的图片的帖子按钮,我认为formData不会清除。

I am using formData for Ajax Image Uploading, when I am submit first time it will successfully upload, and again click post button that image also posted to server, I think formData will not clear.

我的代码

$("#postsubmitimage").click(function () {
                var formData = new FormData();
                for (var i = 0; i < files.length; i++) {
                    if (files[i].type.indexOf('image/') === 0) {
                        formData.append("files", files[i]);
                    }
                }
                    $.ajax({
                        type: "POST",
                        url: '/Ajax/Fileupload/',
                        data: formData,
                        dataType: 'json',
                        contentType: false,
                        processData: false,
                        success: function (json) {
                            $('#textpostimage').val('');
                        }
                    });
            })


推荐答案

我认为这是因为在ajax提交后,您的文件变量未被清除。在您的单击处理程序中,您确实创建了一个空的 FormData 对象,但随后您继续用文件中的旧引用填充该对象<​​/ code >,显然不清楚。

I think this happens because your files variable is not cleared after the ajax submission. In your click handler you create an empty FormData object indeed, but then you proceed to fill that object with old references from files, which apparently are not clear.

我建议在ajax成功完成后进行一些清理

What I suggest is doing some cleanup after a successful ajax completion

success: function (json) {
    // Supposing #textpostimage is your file input, you are already clearing it
    $('#textpostimage').val('');
    // Also clear your "files" reference
    files = [];
}

要清除整个表格,您可以 $( '#myForm')。get(0).reset()

To clear the whole form you could do $('#myForm').get(0).reset()

我不知道你什么时候填充文件,其值为 #textpostimage ,但如果您希望多个表单提交工作,请确保不仅在页面加载时执行此操作。

I don't know at what time you populate files with values from #textpostimage, but make sure to do it not only on page load, if you want to have multiple form submissions working.

这篇关于如何使用javascript清除/重置formData()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆