2014-02-05 71 views
0

我有这样的代码。我尝试做递归回调函数doWork。当我运行这个时,我从ajax得到了第一个响应,在“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

可能重复的[调用JavaScript函数递归](http://stackoverflow.com/questions/7065120/calling-a-javascript-function-recursively) – Cerbrus

回答

0

您应该使用.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(); 
});