Submit a form only once; don't submit when page is refreshed

强颜欢笑 提交于 2020-01-03 05:08:06

问题


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.



来源:https://stackoverflow.com/questions/9269119/submit-a-form-only-once-dont-submit-when-page-is-refreshed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!