Prevent or clear back history with form submission
I have a small quiz web application to deploy.
Basically I have 2 pages, '1) Quiz page' and '2) Result page'. Upon submitting the Quiz form, it will generate the result on the result page for the user. However I need to prevent user from clicking on back button or keying in Backspace on the keyboard.
I researched开发者_JAVA百科 the use of 'location.replace()' but have no idea how can I implement it within my form:
<form id="quiz" name="quiz" method="post" action="result.php">
...
<input type="submit" name="Submit" value="Submit" />
</form>
I would like to know if there is any way for me to use location.replace() within the form, or otherwise, any other way that I could prevent/clear user from getting back to the history page.
Thank you.
If you're afraid of users going back checking answers then resubmitting the form, I think you're approaching the problem from the wrong end.
What you need to do is give each quiz "session" a unique ID at startup. Then do a check on form submit to see if the quiz session has already been submitted. If it has already been submitted, deny it.
There is no way to prevent a user from clicking "Back" in his/her browser. One way to accomplish the aim is to submit the form using AJAX. When he/she clicks back, it will not go to the quiz but to the previous page.
The following fully-working example uses the jQuery library:
<html><head></head><body>
<div id="form_wrap">
<form onsubmit="send_form(this);return false">
...
<input type="submit" />
</form>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
function send_form(form) {
jQuery.post('result.php', jQuery(form).serialize(), function(data) {
jQuery('#form_wrap').html(data);
});
}
</script>
</body></html>
just submit form in onload event.
<body onload="document.forms[0].submit()">
This will skip adding page to history.
精彩评论