捕获表单提交不起作用

Catch form submit not working

我一直在尝试几个示例来捕获表单的提交,但我得到的只是重新加载页面。

jQuery(document).ready(function($)
{
    var frm = $('#export-form');
    //Catch the submit
    frm.submit(function(ev) {
        console.log("Here I am")  //Not visible in Firebug
        // Prevent reload
        ev.preventDefault();

        $.ajax({
            type        : 'POST', 
            url         : 'libs/GenerateCSV.php', 
            data        : 'export', 
            success     : function (data) {
                alert('success'); // Temporary debugging, later a redirection is planned
            }
        });
    });
});

但是脚本永远不会执行。 我尝试使用 onsubmit 调用,但结果相同。 谁能帮帮我?

您的代码示例没有任何问题。

您确定 jQuery 在您的脚本之前加载了吗?

此外,您可以将代码包装在 document.ready 语句中:

jQuery(document).ready(function($)
{
    // your code goes here
});

试试这个方法

<!-- Include jQuery before this code -->
<form id="export-form" method="post" accept-charset="utf-8">
    <a id="submit-form" href="#">Start Download</a>
</form>

<script type="text/javascript">

    $(document).ready(function() {
        $("#submit-form").click(function(){
            $.ajax({
                type        : 'POST', 
                url         : 'libs/GenerateCSV.php', 
                data        : 'export',
                success     : function (data) {
                    alert('success');//Just for debugging, later a redirection to a file is planned 
                }
            });
        });
    });
</script>

锚标记不会自动提交您的表单并重定向您。我总是使用此解决方案来提交表单而无需重定向。您可以在任何您想要的地方重定向成功事件。希望对你有帮助。

检查你的 HTML 代码,我猜你可能在 <input> 中写了 onClick,如下所示:

<input type="submit" value="submit" onClick="this.form.submit(); this.disabled=true; this.value='waiting ...'; ">