简体   繁体   English

防止表单在页面加载时自动重新提交

[英]prevent form from automatically re-submitting on page load

I am using jQuery to point a form's target to an iframe on .submit(). 我正在使用jQuery将表单的目标指向.submit()上的iframe。 This is to upload a file. 这是上传文件。 It works fine, but when the page reloads, and the iframe is appended to the DOM, the iframe automatically resubmits the form, causing the same file to be sent to the server on each page load. 它可以正常工作,但是当页面重新加载并将iframe附加到DOM时,iframe会自动重新提交表单,从而在每次页面加载时将相同的文件发送到服务器。

If I do not include the iframe in the HTML markup, or do not append it to the DOM, this doesn't happen, but of course, I need the iFrame. 如果我不将iframe包含在HTML标记中,或者不将其附加到DOM,则不会发生这种情况,但是我当然需要iframe。

So my question is, how can i prevent this? 所以我的问题是,我该如何预防呢?

:) :)

Andrew 安德鲁

append the iframe to the document body on document ready. 将iframe附加到文档就绪的文档主体上。

$(function(){
    $("body").append("<iframe id='whatever' src='javascript:void(0)' />");
});

So, it turned out that if the iframe exists in the DOM when the user reloads the page, it will trigger the form again, so I simply didn't add the iframe until the user clicks to send the file. 因此,事实证明,如果用户重新加载页面时DOM中存在iframe,它将再次触发表单,因此我只是在用户单击发送文件之前才添加iframe。

The complete code (some is only relevant to my project, but the idea is there: 完整的代码(有些仅与我的项目有关,但是这里的想法是:

function uploadHandler()
{
    if ($.browser.safari || $.browser.opera || $.browser.msie)
    {
        setTimeout(uploadComplete, 5);
    }
    else
    {
        uploadComplete(this);
    }
}


function uploadFile(e)
{

    if($('.uploadFrame').length > 0)
    {
        uploadiFrameNode.remove();
    }
    n = 'f' + Math.floor(Math.random() * 99999);
    uploadiFrameNode = $('<iframe class="uploadFrame invfr" src="about:blank" id="'+n+'" name="'+n+'"></iframe>');
    uploadiFrameNode.load(uploadHandler);
    $('body').append(uploadiFrameNode);
    formNode.attr('action', _ajaxPath  + "?drive=" + drive);
    formNode.attr('target', n);
    formNode.attr('method', 'POST');
    formNode.attr('enctype', 'multipart/form-data');
    formPathNode.val(tree[tree.length - 1].path);
}
function uploadComplete()
{
    refresh(tree[tree.length - 1].path);
    backToMenu();
    fileReset();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM