$.post 안에서 리턴을 못하나요?

$.post 안에서 리턴을 못하나요?

QA

$.post 안에서 리턴을 못하나요?

본문

완성형은 아니지만 

작성하다 보니 아래처럼 코드가 되었습니다.


<?php
include_once ('./_common.php');
include_once (G5_PATH.'/head.php');
?>
<script type="text/javascript">
$(document).ready(function(){
    $(document).on("click", "button", function(){
        var temp = foo(99);
        console.log("함수 리턴값", temp);
    });
});
function foo(idx){
    $.post("./ajax.php", {idx:idx}, function(data){
        console.log("ajax안의 값", data.idx);
        return data.idx;
    }, "json");
}
</script>
<button type="button">버튼</button>

<?php
include_once (G5_PATH.'/tail.php') ;

 

함수안에 $.post안의 data.idx 값을 foo함수 리턴값으로

리턴을 하려면 어떻게 해야 하나요?

 

이 질문에 댓글 쓰기 :

답변 4

이렇게 해보세요



function foo(idx){
    var data_idx;
    $.ajaxSetup({ async: false });
    $.post("./ajax.php", {idx:idx}, function(data){
        console.log("ajax안의 값", data.idx);
        data_idx = data.idx;
    }, "json");
    return data_idx;
}


<script type="text/javascript">
$(document).ready(function(){
    $(document).on("click", "button", async function(){
        var temp = await foo(99);
        console.log("함수 리턴값", temp);
    });
});
async function foo(idx){
    return $.post("./ajax.php", {idx:idx}, function(data){
        console.log("ajax안의 값", data.idx);
        return data.idx;
    }, "json");
}
</script>
<button type="button">버튼</button>

var temp = foo(99);<--- foo를 호출하고 바로 다음행으로 진행 되어버리기 때문에

다음행에서 return값을 못받은 상태로 출력하게 됩니다

굳이 이렇게 할 필요가 있나요?

 $(document).on("click", "button", function(){

     idx = 99;
      $.post("./ajax.php", {idx:idx}, function(data){
       var temp = data.idx;
        console.log(" 리턴값", temp);
    }, "json");       
 });

 

답변을 작성하시기 전에 로그인 해주세요.
전체 57
QA 내용 검색
filter #post ×

회원로그인

(주)에스아이알소프트 / 대표:홍석명 / (06211) 서울특별시 강남구 역삼동 707-34 한신인터밸리24 서관 1404호 / E-Mail: admin@sir.kr
사업자등록번호: 217-81-36347 / 통신판매업신고번호:2014-서울강남-02098호 / 개인정보보호책임자:김민섭(minsup@sir.kr)
© SIRSOFT