2011-12-24 68 views
0

在我的應用程序中,我有一個使用ajax的登錄,它返回一個JSON結果。ajax調用內的jQuery JSON

如果是良好的話,它會返回:

{"authenticated":true,"redirect":"/posts/new"}

如果它是一個失敗了:

{"authenticated":false,"error":"Username or password is incorrect"}

我想要做的就是在我的AJAX成功回調檢查認證是什麼,如果是真的,那麼做一件事,如果它是假的,那麼做另一件事:

success: function (responseHtml) 
{ 
    if(SUCCESS IS TRUE) 
    { 
      window.location.href('REDIRECT'); 
    } 
    else 
    {   
      alert('ERROR MESSAGE'); 
    } 

    console.log(responseHtml); 
} 

任何人都可以幫助我嗎?我看過getJSON的東西,但不知道如何在這裏使用它。由於

UPDATE:全碼

$('form').live('submit', function (event) { 

      var form = $(this); 

      event.preventDefault(); 

      var data = form.serialize(); 

      $('<div id="loading">Loading...</div>').appendTo('#li-submit').hide(); 

      $('#loading').fadeIn(); 

      $.ajax({ 
       type: form.attr('method'), 
       url: form.attr('action'), 
       data: data, 
       success: function (response) 
       { 
        $('#loading').fadeOut(function() { $(this).remove(); }); 

        if(response.authenticated) 
        { 
         window.location.href('url'); 
        } 
        else 
        { 
         alert(response.error); 
        } 
       }, 
       error: function (jqXHR, textStatus, errorThrown) 
       { 
        $('#loading').fadeOut(function() { $(this).remove(); }); 

        alert('Error!'); 
       } 

      }); 

     }); 

回答

2
success: function(response) { 
    if(response.authenticated) { 
     window.location.href('url'); 
    } else { 
     alert('error'); 
    } 
} 

你應該確保你的AJAX配置對象的「的dataType」屬性設置爲「JSON」或者未設置(它會默認爲自動 - 檢測)。

+1

在這種情況下,將'success:function(responseHtml)'改爲'success:function(response)' – 2011-12-24 00:15:41

+1

哦好點。我重命名了它,因爲「responseHtml」不會是HTML,而是JSON。我會更新,謝謝。 – Interrobang 2011-12-24 00:16:32

+0

yep responseHtml沒有意義 – 2011-12-24 00:19:28

0
// if response is already json as you said 
success: function (response) { 
    if(response && response.authenticated) { 
     window.location = response.redirect; 
    } else {   
     alert('ERROR MESSAGE'); 
    } 

    console.log(response); 
}