简体   繁体   中英

prevent form from automatically re-submitting on page load

I am using jQuery to point a form's target to an iframe on .submit(). 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.

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.

So my question is, how can i prevent this?

:)

Andrew

append the iframe to the document body on document ready.

$(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.

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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