请参阅下面的示例。如何从加载的文件中调用我的函数?
这是我的外部文件,加载了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/