2012-10-12 122 views
0

是否有可能在我的JS中添加其他函數,如下所示:?如果在Ajax中添加其他函數Jquery函數

如果響應==成功重定向到家裏
如果響應==未能重定向到失敗

$.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>"); 
    } 
});​ 

回答

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>"); 
    } 
});​ 
+0

我認爲'success'是贊成'done' http://api.jquery.com棄用/jQuery.ajax/ –

+0

@DavidJohnWelsh。一定不行!你爲什麼這麼認爲? – gdoron

+0

@DavidJohnWelsh你可能意思是這樣的:*棄用聲明:jQuery 1.8中不會使用jqXHR.success(),jqXHR.error()和jqXHR.complete()回調。要準備代碼以便最終刪除它們,請使用jqXHR.done(),jqXHR.fail()和jqXHR.always()。*它僅適用於ajax提供的'jqXR' obect returen,而不適用於成功和錯誤屬性。 – gdoron

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"); 
     } 
    } 
}); 
0

你也可以做這樣的事情

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

記住這只是> jQuery的1.8

+0

這不起作用,因爲響應總是成功,但是基於響應,您需要執行一些操作。 –

+0

是的,你的權利。重讀這個問題並進行編輯。 :) – bhb

相關問題