javascript - jQuery - 在加载 ajax 的文件中调用函数

标签 javascript jquery ajax get promise

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

这是我的外部文件,加载了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? 

});

非常感谢任何建议。

最佳答案

// 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);
    }
});

关于javascript - jQuery - 在加载 ajax 的文件中调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21886903/

相关文章:

javascript - 如何通过滚动切换大小写

javascript - Footable doSort 根本不起作用

jquery - 从文本中删除具有特定类的所有元素

javascript - (未捕获的语法错误 : Unexpected token : ) - What to do?

javascript - 将格式不正确的 XML 文档转置为 HTML 无序列表

php - 使用 AJAX 显示进度的 MD5 哈希解码网站

javascript - 结合变化的 Polymer 1.0 Array Observers

javascript - 省略数据表中的列的通用解决方案

javascript - 上下文中 jQuery.ajax() 中出现意外标识符

javascript - 如何删除数组中重复出现的内容?