【问题标题】:jQuery - call functions within a file loaded with ajaxjQuery - 在使用 ajax 加载的文件中调用函数
【发布时间】:2014-03-20 03:53:33
【问题描述】:

请看下面的例子。如何从加载的文件中调用我的函数?

这是我的外部文件,加载了 ajax:

// some-file-name.js
var api = {
    method1: function() {
        // doStuff here
    }
}

在这里我正在加载文件并希望从提供的新方法中调用一些函数:

// load script and do stuff with it when done
$.when(
   $.getScript("some-file-name.js"), 
   $.Deferred(function(deferred) {
       $(deferred.resolve);
})).done(function() {
    // how to call api.method1() when api.method1() gives me undefined? 

});

非常感谢任何建议。

【问题讨论】:

标签: javascript jquery ajax get promise


【解决方案1】:
// 1. $.getScript returns a Promise, no need for custom deferred
// 2. access your response. The Promise passes the response to the 
//    success handler parameter

$.when(
   $.get("some-file-name.js"), // 1
).done(
    function(api) {  // 2
      console.log(api.method1);
    }
});

【讨论】:

  • -1: a) 自定义 deferred 用于等待 DOM 准备好,没有别的 b) 如上所述,回调不起作用。该脚本可能尚未执行。
  • 哦,我有个很好的主意。我什至可以阅读the docs:“一旦脚本加载但不一定执行回调就会触发”如果您了解更多,请告诉我们。
  • a) 将语句包装在 $(document).ready({ }); b) $.getScript 将返回脚本并立即执行它,也许您应该使用 $.get 代替
  • a) 哪个声明,console.log?是的,这也可以,但是 OP 使用 deferred 并没有错。顺便说一句,如果你知道 $.ajax 返回一个承诺,$.when 是多余的。 b) $.get 在这里有什么帮助?难道不是执行脚本,所以api.method肯定会失败吗?
  • 请注意这不是我的问题 :-) 不,在那个 sn-p 中,ajax 请求只会在 DOM 准备好之后开始,这不是预期的行为。但是你可以做$.get("…").done(function(resp) { $(function() { // do whatever we want api.method1(); }); })
猜你喜欢
  • 2011-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-14
  • 2020-08-14
  • 1970-01-01
  • 1970-01-01
  • 2021-07-25
相关资源
最近更新 更多