如何使用getScript知道Ajax调用何时完成?

3
我正在使用jQuery的getScript方法将许多JS文件加载到我的页面中。这些JS文件中的每一个都有一个AJAX调用,从数据库中获取数据。
我在getScript上使用.done方法来查看所有文件是否已加载完成,但我需要等待所有AJAX调用也完成后再执行操作。
如何通过getScript等待已包含文件中的AJAX调用完成后再执行操作?
$.getMultiScripts(moduleIncludes, 'includes/js/modules/').done(function() {
    // All of the JS files have been included but we need to wait until those files have finished their AJAX call.     
});

// Get array of JS scripts to load
$.getMultiScripts = function(arr, path) {

  var _arr = $.map(arr, function(scr) {
      return $.getScript((path || "") + scr);
  });

  _arr.push($.Deferred(function(deferred) {
      $(deferred.resolve);
  }));

  return $.when.apply($, _arr);
}

让所有的程序在某个地方写下它们的完成状态。然后,您需要查询那个“某个地方”(服务器、本地存储或其他)以检查是否所有的程序都已完成。 - pah
安装一个 setTimeout 处理程序,它既检查完成情况,又在一切都完成(加载)时执行进一步的代码。 - pah
如果您知道文件的数量,可以使用计数器。 - Ismail RBOUH
_arr.push($.Deferred(function(deferred) { $(deferred.resolve); }));的目的是什么? - guest271314
@guest271314 - https://dev59.com/M2gt5IYBdhLWcg3wywlJ#11803418 - SBB
显示剩余3条评论
1个回答

5
你可以使用.ajaxStop() 每当一个Ajax请求完成时,jQuery会检查是否还有其他未完成的Ajax请求,如果没有了,jQuery就会触发ajaxStop事件。
$(document).on("ajaxStop", function() {
  // do stuff when all `$.ajax()` call have complete
  $(document).off("ajaxStop")
});

$.getMultiScripts(moduleIncludes, 'includes/js/modules/').done(function() {
    // All of the JS files have been included but we need to wait until those files have finished their AJAX call.     
});

另一种方法是使用 $.when.apply() 两次。也就是说,将ajax调用推入第二个数组中。 "module1.js"
data.push($.get("/path/to/module1-resource"))

var modules = ["module1.js", "module2.js", "module3.js"];
// declare global `data` array
data = [];

$.getMultiScripts = function(arr, path) {

  var _arr = $.map(arr, function(scr) {
      return $.getScript(scr)
  });

  return $.when.apply($, _arr.concat($.when()))
}

$.getMultiScripts(arr)
.then(function() {
  console.log("getScript calls", arguments)
  $.when.apply($, data).then(function() {
    console.log("ajax calls", arguments)
  })
});

plnkr http://plnkr.co/edit/si2EsUZOciOwU4nAPlS9?p=preview

这是一个名为“plnkr”的网站链接,可以用来分享和编辑在线代码。

那真是太酷了 - 我想那会解决我的需求。 - SBB

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接