隐藏的iFrame文件上传在每次后续提交时都会提交额外的时间

Hidden iFrame file upload submits an extra time on each subsequent submit

本文关键字:提交 时间 文件 iFrame 隐藏      更新时间:2023-09-26

我正在尝试为我的网站创建一个简单的文件上传表单。我使用了一个隐藏的iFrame来实现"ajax"风格,这样我就可以让用户使用相同的表单一个接一个地上传文件

现在我有一个<input type="file" />表格。我所做的是,当输入字段发生变化(用户选择一个文件)时,它应该将目标设置的表单提交给iFrame,iFrame加载php脚本,然后重置输入字段以允许用户再次上传。似乎发生的情况是,表格是根据提交次数提交的。例如,如果你在页面加载时按下按钮,它将提交一次,但如果你再次按下按钮(不重新加载页面),它将两次提交,当你第三次按下按钮时,它将三次提交表单,依此类推

这是我在输入更改时的javascript

newupload是输入的id
newimgform是表单的id
postframe是iframe 的id

$("#newupload").change(function() {
    var max = 5242880, iframe = $("#postframe"), iframeContents;
    $('#newimgform').attr("action", "uploadPicture.php")
    $('#newimgform').attr("method", "post")
    $('#newimgform').attr("MAX_FILE_SIZE", max)
    $('#newimgform').attr("enctype", "multipart/form-data")
    $('#newimgform').attr("encoding", "multipart/form-data")
    $('#newimgform').attr("target", "postframe")
    $('#newimgform').submit();
    $("#postframe").load(function() {
        iframeContents = jQuery.parseJSON($(this.contentDocument).find('body').html());
        alert(iframeContents.filename);
    $("#newimgform")[0].reset();
    });
});

我找了其他人尝试这个,我在这里看到了一些关于提交被绑定多次的答案,我需要像$('#newimgform').unbind("submit").submit();一样使用unbind,但这似乎没有任何作用。我不能使用任何flash上传器或任何东西,所以这必须是纯html/javascript.php。

您可以移出iframe加载处理程序,因为不需要每次上传文件时都添加它。你也可以像这样优化你的代码。

$("#newupload").change(function() {
    $('#newimgform').attr({
       action: "uploadPicture.php",
       method: "post",
       MAX_FILE_SIZE: 5242880,
       enctype: "multipart/form-data",
       encoding: "multipart/form-data",
       target: "postframe",
    }).submit();
});
$("#postframe").load(function() {
    var iframeContents = jQuery.parseJSON($(this.contentDocument).find('body').html());
    alert(iframeContents.filename);
    $("#newimgform")[0].reset();
});

load事件处理程序绑定到change事件处理程序之外。实际上,每次更改#newupload的值时,都会有一个新的事件处理程序绑定到#postframe元素:

$("#postframe").load(function() {
    var iframeContents = jQuery.parseJSON($(this.contentDocument).find('body').html());
    alert(iframeContents.filename);
    $("#newimgform")[0].reset();
});
$("#newupload").change(function() {
    $(this).attr("action", "uploadPicture.php")
                    .attr("method", "post")
                    .attr("MAX_FILE_SIZE", 5242880)
                    .attr("enctype", "multipart/form-data")
                    .attr("encoding", "multipart/form-data")
                    .attr("target", "postframe")
                    .submit();
});

您也可以在load事件处理程序每次运行时解除绑定,但这在您的情况下似乎没有必要。$(this).unbind('load');是您需要添加到load事件处理程序中的全部内容。

此外,您还可以对其进行大量优化。在jQuery中,当我们链接函数调用时,您正在反复使用相同的选择器。