Submit a form only once; don't submit when pag

2019-06-14 13:43发布

问题:

This question is so basic that I'm almost embarrassed to ask it, but it's got me stumped. I've written a short code snippet to explain it:

<form id="MyForm" method="post" enctype="multipart/form-data" >
    <input type="file" id="get_file" name="get_file" >
    <input type="submit" name="submitForm" value="Submit" >
</form>

<?php
    if (isset($_POST['submitForm'])) {
    echo "<script type='text/javascript'>alert('Selected')</script>";
} else {    
    echo "<script type='text/javascript'>alert('Not selected')</script>";
}
?>

When I load this page the first time, the alert says "Not selected". Good. I submit the form and the alert says "Selected". Also good. But when I refresh the page, it's still "Selected". I don't understand why the "IF" statement allows this to happen. I want my form to submit data once and not do it again until my user does it, not every time the page refreshes.

This seems like the kind of question that noobs ask when they're too lazy to use Google, but I've looked (there are even some threads on this site that sort of address this issue, but nobody has presented a solution). I've read up on HTML forms, but I still don't get it.

Is this something everyone knows but me? Can somebody clue me in? Thanks.

EDIT: If anybody ever stumbles over this thread and needs a quick-and-dirty fix, here's one I just stumbled on. Just press the select key again, easily done using jQuery. The form is resubmitted, but the form variables are all cleared. Not elegant, maybe, but it works perfectly.

回答1:

When you reload the page, it is resubmitting the POST request, which means the submitForm=Submit is part of the request body.

You should use the Post/Redirect/Get pattern to avoid this.