在Ajax Jquery函数中添加if else函数

时间:2012-10-12 03:34:58

标签: jquery ajax

是否可以在我的JS中添加其他功能:?

如果响应==成功重定向到主页
如果响应==失败重定向失败

$.ajax({
    type: "POST",
    url: action,
    data: form_data,
    success: function(response) {
        if (response == 'success') 
            window.location.replace("home");
        else 
            $("#message").html("<div class='error_log'><p class='error'>Invalid username and/or password.</p></div>");
    }
});​

3 个答案:

答案 0 :(得分:6)

success: function(response) {
    if (response == 'success') 
        window.location.replace("home");
    else if (response == "failed") 
        window.location.replace("failed");
    else 
        $("#message").html("<div class='error_log'><p class='error'>Invalid username and/or password.</p></div>");
}​

或者你的意思是:

$.ajax({
    type: "POST",
    url: action,
    data: form_data,
    error: function() {
        window.location.replace("Failed");
    },
    success: function(response) {
        if (response == 'success') 
            window.location.replace("home");
        else 
            $("#message").html("<div class='error_log'><p class='error'>Invalid username and/or password.</p></div>");
    }
});​  

答案 1 :(得分:1)

使用此:

$.ajax({
    type: "POST",
    url: action,
    data: form_data,
    success: function(response)
    {
        if (response == 'success')
            window.location.replace("home");
        else if (response == 'failure')
        {
            $("#message").html("<div class='error_log'><p class='error'>Invalid username and/or password.</p></div>");
            window.location.replace("failed");
        }
    }
});

答案 2 :(得分:0)

您也可以这样做

$.ajax( "example.php" )
   .done(function(msg) { 
      alert("success");
      if(msg == "success") ...
      else ... 
   })
   .fail(function() { alert("error"); });

请记住,这仅适用于&gt; jQuery-1.8