2014-02-05 6 views
0

이 코드가 있습니다. 재귀 콜백 함수 doWork를 시도합니다. 내가 이걸 실행할 때 나는 아약스의 첫 반응을 얻었고 "nextWord"div에서 나는 두 번째 단어를 얻었다. 하지만 두 번째 응답을 얻으려면 콜백 doWork 함수를 사용할 수 없습니다.jquery ajax 재귀 호출

제안 사항이 있으십니까?

<script> 

    function doWork() { 
     $.ajax({ 
      type: "POST", 
      url: "eu.php", 
      data: { word: $('#nextWord').html()}, 
      dataType: 'json', 
      success: function(msg) { 
       alert($('#nextWord').html()); 
       $("#nextWord").html(msg.nextWord); 
       $("#query").html(msg.query); 
       doWork(); 
       //doWork; --- I try and this 
      },     
     }); 
    } 

    $(function() { 
     doWork(); 
    }); 
</script> 


<div id="nextWord">firstword</div> 
<div id="query"></div> 
+0

중복 가능성 [자바 스크립트 함수 호출 재귀 (http://stackoverflow.com/questions/7065120/calling-a-javascript-function-recursively) – Cerbrus

답변

0

똑같은 두 핸들러를 피하기 위해 success 콜백 대신 .then를 사용해야합니다.

<script> 

function doWork() { 
    $.ajax({ 
     type: "POST", 
     url: "eu.php", 
     data: { word: $('#nextWord').html()}, 
     dataType: 'json', 
     success: function(msg) { 
      alert($('#nextWord').html()); 
      $("#nextWord").html(msg.nextWord); 
      $("#query").html(msg.query); 

     },     
    }).then(function(data){ 
       doWork(); 
       }); 
} 

$(function() { 
    doWork(); 
});