2012-05-09 2 views
0

가능한 복제를 작동하지 않습니다
jQuery: Return data after ajax call successJQuery와 함수 반환은

내가 다른 함수에서 호출되어 다음과 같은 기능을 가지고있다. 함수가 작동하는지 여부를 확인하려면 무언가를 반환해야합니다.

//Function to close any existing connection 
function closeConnection(manual) { 
    //Establish connection to php script 
    $.ajax({ 
     type: 'POST', 
     url: 'action/chat/closeconnection.php', 
     success: function (feedback) { 
      //If this function was called manually, also empty chatTextDiv and fade out chatDiv 
      if (manual == true) { 
       //Stop getting messages 
       clearInterval(setintervalid); 
       //Fade out chatDiv 
       $('#chatDiv').fadeOut(100); 
       //Empty chatTextDiv 
       $('#chatTextDiv').html(''); 
       //Fade in openChatDiv 
       $('#openChatDiv').fadeIn(100); 
      } 
     } 
    }).error(function() { 
     //Append with connection error - user doesn't know that he is disconnected first so it is better to say this as the function will return false and stop other functions 
     if (manual != true) { 
      $('#chatTextDiv').append('You could not be connected. Please try again later.<hr/>'); 
      //Stop getting messages 
      clearInterval(setintervalid); 
      var closeconnectionsuccess = false; 
     } 
     elseif(manual == true) { 
      $('#chatTextDiv').append('You could not be disconnected. Please try again later.<hr/>'); 
      var closeconnectionsuccess = true; 
     } 
    }); 

    return closeconnectionsuccess; 
} 

실제로 함수의 성공을 반환하려는 마지막 행에 관한 것입니다. 코드가 작동하지 않습니다. 왜 안돼?

+4

을 모두 함께 지금 : 당신은 비동기 함수 값을 반환 할 수 없습니다. – Blazemonger

+2

구문 오류가 있습니다. 'elseif (manual == true) // "else if"와 공백이 있습니다. – elclanrs

답변

3

@Rockitsauce가 말한 것처럼 closeconnectionsuccess 변수는 함수의 범위에 없으므로 그 시점에서 액세스 할 수 없습니다. 그러나 더 중요한 것은 jQuery의 비동기 함수를 사용한다는 점을 고려해야한다는 것입니다. closeConnection 함수는 콜백 (success, error)이 호출되기 전에 실행을 완료합니다. HTTP 요청이 완료된 후 결과를 검색하려면 자체 함수에 콜백 함수를 추가해야하므로 비동기로 만들어야합니다.

이 코드는 그러므로 작동합니다 :

//Function to close any existing connection 
function closeConnection(manual, callback) { 
//Establish connection to php script 
$.ajax({ 
    type: 'POST', 
    url: 'action/chat/closeconnection.php', 
    success: function(feedback) { 
     //If this function was called manually, also empty chatTextDiv and fade out chatDiv 
     if(manual==true) 
     { 
      //Stop getting messages 
      clearInterval(setintervalid); 
      //Fade out chatDiv 
      $('#chatDiv').fadeOut(100); 
      //Empty chatTextDiv 
      $('#chatTextDiv').html(''); 
      //Fade in openChatDiv 
      $('#openChatDiv').fadeIn(100); 
     } 
    } 
}).error(function() { 
    //Append with connection error - user doesn't know that he is disconnected first so it is better to say this as the function will return false and stop other functions 
    if(manual!=true) 
    { 
     $('#chatTextDiv').append('You could not be connected. Please try again later.<hr/>'); 
     //Stop getting messages 
     clearInterval(setintervalid); 
     callback(false); 
    } 
    elseif(manual==true) 
    { 
     $('#chatTextDiv').append('You could not be disconnected. Please try again later.<hr/>'); 
     callback(true); 
    } 
}); 
} 

closeConnection(manual, function(success) { 
    //Process result 
}); 
+0

이것이 올바른 접근 방법입니다. –

1

closeconnectionsuccess 변수가 범위를 벗어납니다.

+2

설명해주십시오. – Blazemonger

+0

요청 완료 후 작업을 수행 할 수 있도록 콜백 함수를 추가하는 것이 좋습니다. –

1

ajax 호출은 비동기입니다. 따라서 함수는 아약스 호출이 반환되기 전에 끝나게됩니다.

아약스 호출이 완료되면 콜백 함수를 호출하거나 이벤트를 트리거해야합니다.