2013-12-11 2 views
1

내가 이것에 대해 많은 글을 통해 갔다 .post,하지만 나를 위해 일하는 어떤 해결책을 찾기 didnt는 - 코드 정리 :캔트 액세스 변수는

$('#form-new').submit(function(e){ 
    e.preventDefault(); 

    $curForm = $(this); 
    $textbox = $('.new-box' ,this); 

    window.tmp_input_ok = false; 

    var wasError = false; 
    if($.trim($textbox.val()) == ""){ 
     wasError = true; 
    }  

    if(wasError){ 
     //possible message 
    } else{ 

     var jqxhr = $.post(
     $(this).attr('action'), 
     $(this).serialize(), 
     function(data, textStatus, jqXHR){ 

      if(data=="200"){ 
      console.log('post OK'); //this shows in console! 
      window.tmp_input_ok = true; 
      } else{ 
      console.log('not OK');  
      } 

     } 
    ).fail(function() { 
     console.log('POST fail)'); 
     });  

    } 

    //however, window.tmp_input_ok is false here so the textbox does not empty: 
    if(window.tmp_input_ok == true) $textbox.val(''); 
     else console.log('input not ok :('); //and this is outputted to console 

    }); 

Originaly, 단지 var tmp_input_ok = false 초기화 한 후 작업이 있었다 tmp_input_ok 변수가 있지만 작동하지 않아서 글로벌 창을 시도했지만 ... 작동하지 않습니다 ... 필사적이기 시작했습니다.

+6

'$ .post()'호출은 비동기식입니다. 이 함수는 즉시 반환하지만 전달한 콜백은 HTTP 응답을받을 때까지 호출되지 않습니다. – Pointy

답변

2

if 문은 호출이 완료되기 전에 실행됩니다.

$.post

는 게시물 이미 .fail() 사용하는

을 처리하는 동안 당신은 완료에 항상 if 문을 실행하거나에 추가하려는 경우, 당신은 .always()을 추가 할 수 있습니다 비동기 호출하고 코드의 나머지 부분은 계속입니다 당신의 .success() 호출이 유사, 성공하면 당신은 단지 그것을 확인하려는 경우 : 호출이 비동기이기 때문에

if (wasError) { 
    //possible message 
} else { 
    var jqxhr = $.post($(this).attr('action'), $(this).serialize(), function (data, textStatus, jqXHR) { 
     if (data == "200") { 
      console.log('post OK'); //this shows in console! 
      window.tmp_input_ok = true; 
     } else { 
      console.log('not OK'); 
     } 

     // either add it here if you only want to process it on success 
     if (window.tmp_input_ok == true) $textbox.val(''); 
     else console.log('input not ok :('); 
    }).fail(function() { 
     console.log('POST fail)'); 
    }).always(function(){ // or add it here if you always wan to execute on completion regardless of fail or success 
     if (window.tmp_input_ok == true) $textbox.val(''); 
     else console.log('input not ok :('); 
    }); 
} 
+1

가독성과 일관성을 위해'.fail()'과'.always()'처럼'.done()'함수에 success handler 코드를 넣었습니다. – Simon

+0

아아 비동기 처리에 대해 잊어 버렸습니다 ... 그게 문제입니다. 체크 아웃 해 봅시다 ... –

+0

작동 중입니다! :) (그냥 내 인생을 구해 줬어 : P), BTW - 항상() - 성공 이후에 항상 실행되고 실패가 처리됩니까? –

1

당신의 XHR 요청이는 onSuccess 콜백이 이유입니다. 예를 들어

테이크 코드의 간단한 비트 :

성공 콜백은 오히려 코드 줄이 읽을 때보다 요청이 성공적으로 수신 될 때 호출되는 무언가로 설정되어
$.get(
    '/foo', 
    function(){ 
     alert("data received"); 
    } 
) 

alert ("End of script reached"); 

브라우저.

전체 XHR 요청에 100 밀리 초가 걸리기 때문에 "데이터 수신 완료"알림 앞에 "스크립트 도달 범위 끝"알림이 표시되는 경우가 많으며 그 중 몇 줄을 읽는 것이 그 중 일부일 것입니다.

상태에 대한 응답이 있는지 여부에 따라 달라지는 코드는 콜백에 의해 호출되어야합니다. 자세히 설명하기에는이 작업을 수행 할 수있는 방법이 너무 많습니다.