2011-12-24 2 views
0

내 응용 프로그램에서 JSON 결과를 반환하는 ajax를 사용하여 로그인했습니다. 그것의 경우jQuery JSON in ajax call

성공은 그것으로 반환합니다

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

를 그것은 다음 실패의 경우

내 아약스 성공 콜백이

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

내가하고 싶은 것은 내부 어떤 인증인지 확인하고 그것이 사실이라면 한 가지를하고 거짓이면 다른 것을하십시오 :

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

에게'성공 : 기능의 성공 '에 (responseHtml)': 기능 (응답)' –

+1

오 좋은 점. "responseHtml"은 HTML이 아니기 때문에 JSON으로 바꿨습니다. 나는 갱신 할 것이다, 고마워. – Interrobang

+0

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