为什么警报会重定向我的页面

Why does an alert redirect my page?

本文关键字:我的 重定向 为什么      更新时间:2023-09-26

为什么每次我向ajaxform发出警报时,页面都会重定向到其php脚本? 但是当我删除警报时,ajax 不会重定向它。我不希望我的页面重定向到它的 php 脚本。

$(document).ready(function(){
           $("#save").click(function(){
           $("#f1").ajaxForm({
                    alert("Submit Successful!");
                    });//ajaxform
    });
});

替换

$("#save").click(function(){

$("#save").click(function(e){
   e.preventDefault();

将事件作为参数传递并使用event.preventDefault()因此页面不会被重定向。

Official Document

你没有正确使用几件事。试试这个:

$(document).ready(function() {
    $("#save").click(function(e) {
        e.preventDefault(); //cancel default action (not strictly necessary...)
        $("#f1").ajaxForm(function() { //N.B. 'function() ' added - before it was an object!
            alert("Submit Successful!");
        });
    });
});

尝试停止默认事件行为。

 $("#save").click(function(e){ 
    e.preventDefault();

使用 return false : 停止对服务器的请求

$(document).ready(function () {
     $("#save").click(function () {
         $("#f1").ajaxForm(function(){
             alert("Submit Successful!");
             return false;//add return false to stop the request to server
         }); //ajaxform
     });
 });
这是

正常行为(如果单击的元素是指向另一个页面的锚标记):您单击一个链接,它会重定向您的页面。
如果你想将该链接用作按钮并绑定某个操作,你绝对应该停止链接的正常行为:防止它重定向页面。
这可以通过多种方式实现,但最好的方法(至少从语义角度来看)是在实际点击事件上调用 preventDefault 方法:

$('a').on('click', function(event){
    // prevents the normal behavior of this "click" action
    // in this case, it prevents the link from changing the url
    event.preventDefault();
    //.. your logic here
});

添加preventDefault()return false;

$("#save").click(function(e) {
    $("#f1").ajaxForm({
        alert("Submit Successful!");
    });//ajaxform
    e.preventDefault();
    //or
    return false;
});

试试这个使用 preventDefault()

$(document).ready(function(){
    $("#save").click(function(e){
       //Stay in the same page
       e.preventDefault();
        $("#f1").ajaxForm({
            alert("Submit Successful!");
        });//ajaxform
    });
});