简体   繁体   English

使用Ajax的JavaScript / jQuery回调

[英]JavaScript/jQuery callback using Ajax

I'm having trouble with my functions running before Ajax requests (the first to a local JSON, the second to an online resource) have finished. 我在Ajax请求(第一个到本地JSON,第二个到在线资源)完成之前运行函数时遇到了麻烦。

In this example I want countTheMovies to run at the end after my application has got all the information it needs and populated the divs. 在此示例中,我希望countTheMovies在我的应用程序获得所需的所有信息并填充div后最后运行。 Instead it's running straight away. 相反,它立即运行。

I tried to delay it using an if condition, but with no joy. 我尝试使用if条件延迟它,但没有任何乐趣。 I've also tried with callbacks, but think I must be getting those wrong (I'm assuming callbacks are the answer). 我也尝试过使用回调,但是我想我一定弄错了(我以为回调是答案)。 I'm aware of timed delays, but because in the actual project I'm sourcing 250+ movies (and because a timed delay seems like cheating) I thought I'd ask here instead. 我知道定时延迟,但是因为在实际项目中我要采购250部以上的电影(并且由于定时延迟看起来像是在作弊),所以我想我会在这里询问。

Can anyone recommend JavaScript or jQuery code to fix this problem? 谁能推荐JavaScript或jQuery代码来解决此问题?

$(function(){
  getMovieList();
});

function getMovieList() {
  $.ajax({
    url: "movielist.json",
    type: "GET",
    dataType: "JSON",
    success: function(data) {
      for (var i = 0; i < data.length; i++) {
        var title = data[i].title.toLowerCase().split(" ").join("+");
        var year = data[i].year;
        i === data.length - 1
          ? getMovieInfo(title, year, true)
          : getMovieInfo(title, year, false);
      }
    }
  });
}

function getMovieInfo(title, year, isLast) {
  $.ajax({
    url: "https://www.omdbapi.com/?t=" + title + "&y=" + year + "&plot=short&r=json",
    type: "GET",
    crossDomain: true,
    dataType: "JSON",
    success: function(val) {
      if (!val.Error) {
        movie = title.replace(/[^a-z0-9\s]/gi, '');
        $("#app").append(
          // appending info to divs
        );
      }
    }
  });
  if (isLast) countTheMovies();
};

function countTheMovies() {
  $("#app").append("There are " + $(".movie").length + " movies.");
}

A plunker of my failings: https://plnkr.co/edit/0mhAUtEsaOUWhkZMJqma?p=preview 我失败的一个缩影: https ://plnkr.co/edit/0mhAUtEsaOUWhkZMJqma?p = preview

You've almost got it! 您已经快知道了!

The same way that you call getMovieInfo in the success callback of getMovieList , you should be calling countTheMovies in the success callback of getMovieInfo . 您致电用同样的方法getMovieInfo在成功回调getMovieList ,你应该叫countTheMovies在成功回调getMovieInfo

As Jacob said above, move the countTheMovies call inside the AJAX request. 正如Jacob所说,将countTheMovies调用移到AJAX请求中。

 $(function(){ getMovieList(); }); function getMovieList() { $.ajax({ url: "movielist.json", type: "GET", dataType: "JSON", success: function(data) { for (var i = 0; i < data.length; i++) { var title = data[i].title.toLowerCase().split(" ").join("+"); var year = data[i].year; i === data.length - 1 ? getMovieInfo(title, year, true) : getMovieInfo(title, year, false); } } }); } function getMovieInfo(title, year, isLast) { $.ajax({ url: "https://www.omdbapi.com/?t=" + title + "&y=" + year + "&plot=short&r=json", type: "GET", crossDomain: true, dataType: "JSON", success: function(val) { if (!val.Error) { movie = title.replace(/[^a-z0-9\\s]/gi, ''); $("#app").append( // appending info to divs ); if (isLast) countTheMovies(); } } }); }; function countTheMovies() { $("#app").append("There are " + $(".movie").length + " movies."); } 

如果希望成功运行,只需将countTheMovies()逻辑放入countTheMovies() AJAX请求的success回调中getMovieInfo

You can call your countTheMovies() function from inside the success field of your Ajax call. 您可以从Ajax调用的success字段内部调用countTheMovies()函数。 This way it will make the function call when you intend it to. 这样,它将在您需要时调用函数。

Try out this 试试这个

$(function(){
      getMovieList();
    });

    function getMovieList() {
    $.when( $.ajax({
        url: "movielist.json",
        type: "GET",
        dataType: "JSON",
        success: function(data) {
          for (var i = 0; i < data.length; i++) {
            var title = data[i].title.toLowerCase().split(" ").join("+");
            var year = data[i].year;
            i === data.length - 1 
              ? getMovieInfo(title, year, true) 
              : getMovieInfo(title, year, false);
          }
        }
      }) ).then(function( data, textStatus, jqXHR ) {
      countTheMovies();
    });
    }

      function getMovieInfo(title, year, isLast) {
      $.ajax({
        url: "https://www.omdbapi.com/?t=" + title + "&y=" + year + "&plot=short&r=json",
        type: "GET",
        crossDomain: true,
        dataType: "JSON",
        success: function(val) {
          if (!val.Error) {
            movie = title.replace(/[^a-z0-9\s]/gi, '');
            $("#app").append(
              // appending info to divs
            );
          }
        }
      });
    };
    function countTheMovies() {
      $("#app").append("There are " + $(".movie").length + " movies.");
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM