簡體   English   中英

Ajax/Jquery 重定向調用不起作用

[英]Ajax/Jquery Redirect call does not work

因此,從我的 php 中,我正在回顯 {error:1}:

$(document).ready(function(){
    $('#form').submit(function(e){
        register();
    });
});

function register(){
    $.ajax({
        type:"POST",
        url:"submit.php",
        async : false,
        data: $('#form').serialize(),
        dataType: "json",
        success: function(msg){
            if(parseInt(msg.error)==1){
                window.location="index.html";
            }
            else if(parseInt(msg.error)==0){  
                $('#error_out').html(msg.error);
                e.preventDefault();
            }
        }
    });
}

但它不想重定向。 相反,它返回帶有 1 的“submit.php”。

好吧,你不能只返回 1,因為那不會是 JSON。 如果您只是返回“1”並對其執行 parseInt,請將 dataType 設置為“html”。


如果您想要 JSON,請在您的 PHP 中執行此操作:

$return = array('code'=>1);
echo json_encode($return);

您的“成功” function 如下所示:

if(msg.code==1){
    window.location="index.html";
}
else if(msg.code==0)
{
    $('#error_out').html(msg.code);
    e.preventDefault();
}
else 
{ 
   // handle any other return value.
}

好的,我的錯是沒有正確閱讀問題。 問題是您正在提交表單,並且沒有正確取消它。 在您的事件處理程序中執行此操作:

$(document).ready(function(){
    $('#form').submit(function(e){
        e.preventDefault();
        register();
    });
});

您可以刪除失敗案例中的那個。 那個沒有做任何事情,因為在異步 function 回來(如果它確實這樣做的話)時,堆棧已經被清除了。

您必須防止表單自行提交。

$(document).ready(function(){
    $('#form').submit(function(e){
        register();

        e.preventDefault(); // Or return false;
    });
});

您的表單提交並且 ajax 沒有機會進行其回調。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM