Ajax 提交重定向到新页面(不应该)

Ajax submit redirects to new page (should not)

本文关键字:不应该 新页面 提交 重定向 Ajax      更新时间:2023-09-26

我不知道为什么我不能用这段代码正确地做ajax魔术。它只是在服务器处理请求时重定向到新页面。我尝试在jquery函数中放置一个console.log("test");,但它从未被调用。所以我猜表单提交永远不会通过我的 ajax,而是直接进入服务器。

$("#startTest").submit(function(e)
            {
                console.log("test"); //This is never called
                e.preventDefault();
                $.ajax(
                {
                    url : 'handler',
                    type: "POST",
                    data : $(this).serialize(),
                    success:function(data) 
                    {
                        alert(data);
                    },
                    error: function() 
                    {
                        alert("failure"); 
                    }
                });
            });

<form id="startTest" method="POST" action="handler">
    <input type="hidden" name="answerswer" value="startTest">
    <input type="text" name="firstname" value="" placeholder="Navn" id="navn" autocomplete="off"><br>
    <input type="submit" name="submit" value="Start test">
</form>

清空表单操作。如果您的表单具有操作,则当您提交脚本时,请遵循该操作。但是您希望通过 ajax 实现该过程,这样您就不会填充动作标记。像这样的东西

<form id="startTest" method="POST" action="">
<input type="hidden" name="answerswer" value="startTest">
<input type="text" name="firstname" value="" placeholder="Navn" id="navn" autocomplete="off"><br>
<input type="submit" name="submit" value="Start test">