我怎么知道用getScript完成Ajax调用的时间? [英] How can I know when Ajax calls are finished with getScript?

查看:90
本文介绍了我怎么知道用getScript完成Ajax调用的时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jQuery getScript将X数量的js文件加载到我的页面中.每个JS页面中都有一个AJAX调用,该调用从数据库中获取数据.

I am using jQuery getScript to load X amount of js files into my page. Each of those JS pages has an AJAX call in it that fetches data from the database.

我正在使用getScript上的.done方法来查看何时已加载所有文件,但是我需要等待所有AJAX调用也都已完成.

I am using the .done method on getScript to see when all of the files have been loaded but I need to wait until all of the AJAX calls have been completed as well.

如何做才能通过getScript等待AJAX​​调用在包含的文件中完成?

How can I go about waiting for the AJAX calls to finish in the included files via getScript before doing something?

$.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);
}

推荐答案

您可以使用 .ajaxStop()

You can use .ajaxStop()

每当Ajax请求完成时,jQuery都会检查是否存在 任何其他未完成的Ajax请求.如果不存在,则jQuery触发 ajaxStop事件.

Whenever an Ajax request completes, jQuery checks whether there are any other outstanding Ajax requests. If none remain, jQuery triggers the ajaxStop event.

$(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调用推入第二个数组


An alternative approach would be to use $.when.apply() twice. That is, push ajax calls into a second array

"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

这篇关于我怎么知道用getScript完成Ajax调用的时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆