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

时间:2014-02-19 16:47:01

标签: 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 个答案:

答案 0 :(得分:0)

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