2014-03-13 2 views
0

이 코드가 있습니다jQuery에서 콜백 함수의 반환 값은 무엇입니까?

function dialogTexts(message) { 
     var langText = $.ajax({ 
      type: 'GET', 
      url: '/index.php/main/dialogtexts', 
      dataType: 'json' 
     }); 

     langText.done(function(data) { 
      message(data); 
     });       

     langText.fail(function(ts) { 
      alert(ts.responseText); 
     }); 
    } 

    dialogTexts(function(text) { 
     alert(text.delete);   
    }); 

내가 (위의 코드에서) 문자열 text.delete을 경고하기 위해 콜백을 사용하고,하지만 내가 좋아하는 뭔가를하고 싶지 :

dialogTexts(function(text) { 
    return text; 
}); 

var deleteConfirmationDialogText = dialogTexts.delete; 
alert(deleteConfirmationDialogText); //deleteConfirmationDialogText is undefined 
+0

"콜백 외부의 데이터에 액세스 할 수없는 이유는 무엇입니까?"- 질문은 현재 가장 일반적인 것입니다. – Johan

답변

1

dialogTexts 인을 함수가없고 .delete 속성이 없습니다. 그래서 사용하려고하면 dialogTexts.deleteundefined입니다. 당신은 당신이하려는 바로 가기를 사용할 수 없습니다.


또한, 여기에서 return 문 :

dialogTexts(function(text) { 
    return text; 
}); 

는 아무것도하지 않고있다. 그것은 단지 dialogTexts() 안에있는 그 콜백의 호출자에게 되돌아 왔고 그 호출자는 리턴 값을 가지고 아무것도하지 않으므로 return text은 아무것도하지 않고있다. 텍스트를 알려하려면, 당신은 당신이 먼저 한 일을해야합니다

: 그것을 할 수있는 유일한 방법이며,이 AJAX와 함께 작동하는 방법 비동기 프로그래밍의 결과이다

dialogTexts(function(text) { 
    alert(text.delete);   
}); 

전화. 콜백 (예 : 약속)을 ​​처리하는 몇 가지 다른 기술이 있지만 콜백 함수에서 비동기 적으로 반환 된 데이터를 처리해야합니다. 비동기 프로그래밍의 성격 일뿐입니다.

+0

코드가 작동하지 않는다는 것을 알고 있습니다. 어떻게하면 좋을지 대답 해주세요 .-) 제발, 제게 올바른 방향으로 나를 가르쳐 주시겠습니까? – bestprogrammerintheworld

+0

@bestprogrammerintheworld - 최신 편집 내용을 읽어보십시오. – jfriend00

+0

좋아, 그럼 내가 원하는 걸 이루고 싶다면 약속을 사용하는거야? – bestprogrammerintheworld