0

我试图在用户离开页面时以编程方式提交表单,无论他们是否点击了“提交”按钮。我过去曾使用此方法从函数中提交表单,但由于某种原因,我无法使用onclick.

当用户单击“提交”按钮时,表单正在正确提交,因此 html 表单和 php 肯定设置正确。我正在使用 jquery-1.8.2

<form name="form2" id="form2" method="post" action="form2-exec.php">
    <!-- Form Elements -->
    <a class="back" href="form1.php" onClick="submitForm()">BACK</a>
    <a href="#" class="next"><input type="submit" value="SUBMIT" /></a>
</form>

<script language="javascript" type="text/javascript">
function submitForm() {
    $("#form2").submit();
}
</script>

我也尝试过使用点击功能

$(".submitForm").click(function () {
$("#taste").submit();
});

并替换 HTML 中的这一行:

<a class="back" href="form1.php" onClick="submitForm()">BACK</a>

和:

<a class="back submitForm" href="form1.php">BACK</a>
4

3 回答 3

1

#Whizkid提交后右击后退按钮不行,试试下面的方法,它利用jquery onbeforeunload事件来测试表单是否已经提交,如果没有则显示消息,通知用户未保存的数据以他们的形式:

$(function() {
        // Set the unload message whenever any input element get changed.
        $('input').change(function() {
            setConfirmUnload(true);
        });

        // Turn off the unload message whenever a form get submitted properly.
        $('form').submit(function() {
            setConfirmUnload(false);
        });
    });

    function setConfirmUnload(on) {
        var message = "You have unsaved data. Are you sure to leave the page?";
        window.onbeforeunload = (on) ? function() { return message; } : null;
    }
于 2013-03-10T19:42:01.897 回答
1

its a tricky situation. if you submit the form, then your back button's redirection wont work. And if you redirect on backbutton click using href,your submit wont work as by the time click function works, your next page will load. How about firing an ajax call using jquery to send your form's data to your server and in the call back function you redirect the page to the previous page?

For details on how to do that, check out this posting: Submit form using AJAX and jQuery

于 2013-03-10T19:22:17.507 回答
0

我通过将 HTML 中的所有必要链接更改为具有名称属性的提交按钮并在 PHP 中添加一条语句来根据用户单击的按钮重定向用户,从而解决了这个问题。

HTML

<input type="submit" name="whereto" value="BACK" />
<input type="submit" name="whereto" value="SUBMIT" />

PHP

// Insert Statement
if ($_POST['whereto'] == 'BACK') {
    header("location: form1.php");
} elseif ($_POST['whereto'] == 'SUBMIT') {
    header("location: form3.php");
}
于 2013-03-12T18:46:59.673 回答