JQuery / Ajax - 完成多个JSON / GET请求时调用函数

时间:2014-01-08 19:35:27

标签: jquery ajax json

我正在制作多个JSON GET,直到满足条件。下面的代码的问题是在满足条件之前(在最终的GET请求之前)调用函数tuneTileLoadedFunction()。我只想在最终加载完成后调用该函数。

我该怎么做?是否与http://api.jquery.com/jquery.when/有关?我已经看过这个了,但是就我已经做过的事情而言,它无法理解它。

当我放置tuneTileLoadedFunction()代替//它不会调用该函数时(我猜因为数据尚未加载)。

谢谢:)

checkIfTuneTileLoaded();  
function checkIfTuneTileLoaded() {

  var tuneTileLoaded = $("a[href*='" + location.pathname + "']").length;
  alert(tuneTileLoaded);

    if (tuneTileLoaded == 1) {

        //whatever

    }  else  {

        alert('tuneTileNotPresent');
        tumblrPostsRetrieved += 20;

        $.ajax({ 
        type: 'GET', 
        url: 'http://api.tumblr.com/v2/blog/onrepeatthisweek.tumblr.com/posts?api_key=cCaCiEE6kd5pInej2YFU0xdC4msLOE3R3IhYXcR1W6Irza8sJq&tag=overandoverandoverandover&offset=' + tumblrPostsRetrieved, 
        data: { get_param: 'value' }, 
        dataType: 'jsonp',
        success: function (data) {
                    for (i = 0; i <= 19; i++) {
                    $('#recent-posts').append('<li><a href="' + data.response.posts[i].post_url +'"> ' + data.response.posts[i].title + '</li>');
                    }
                    maxScrollLeft = document.getElementById("tunesID").scrollWidth - document.getElementById("tunesID").clientWidth;
                    checkIfTuneTileLoaded();
                    tuneTileLoadedFunction();
                    alert('success');
                 }
        });
    }
}

更新/决议:

我没有解决我试图解决的问题(在其中监听带有Ajax请求的递归函数的结束)。我的解决方案不是等待每个请求完成,而是检查每个项目,因为它们是为我所寻找的内容而呈现的:

for (i = 0; i <= 19; i++) {
        $('#recent-posts').append('<li><a href="' + data.response.posts[i].post_url +'"> ' + data.response.posts[i].title + '</li>');
        if (data.response.posts[i].post_url == window.location) {
            tuneTileLoaded = 1;
            tuneTileLoadedFunction();
        }
        }

2 个答案:

答案 0 :(得分:0)

您可能希望将tuneTileLoadedFunction()移出成功调用或将其包装在条件中,否则它将在每次GET请求后执行。

答案 1 :(得分:0)

您可以使用此类问题的承诺。使用$ .Deferred()。请查找文档here。你可以这样做:

function xyz() {
   var dfd = $.Deferred();

   for ( i = 0 ; i < =19 ; i++ ) {
      //do something

      if( condition ) {
        dfd.resolve();
      }

   return dfd.promise();

}

xyz.done( tuneTileLoadFunction );

希望这对你有用。

相关问题