2011-12-24 20 views
0

私のアプリケーションでは、JSON結果を返すajaxを使ってログインしています。それは成功だ場合jQuery JSON with ajax call

することは、それはのように返します。

{"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のconfigオブジェクトの「dataTypeと」属性が設定を「JSON」に設定するか、またはされていないことを確認する必要があります(それが自動にデフォルト設定されます検出する)。

+1

この場合、「success:function(responseHtml)」から「success:function(response)」に変更してください。 –

+1

オハイオ州ポイント。私は "responseHtml"はHTMLではなくJSONであるため、名前を変更しました。私は更新します、ありがとう。 – Interrobang

+0

yep responseHtmlが意味を持たない –

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