[英]How to use function present in the js file (loaded using Ajax) in other sections of script?
我有一個ExtJs應用程序,可以加載很多JavaScript文件。 這會導致大量開銷,因此,我們現在使用Ajax加載javascript文件。
因此,當用戶單擊按鈕時,將使用Ajax通過以下方式加載帶有與按鈕相關的功能的javascript文件:
Ext.Ajax.request({
url:'filePath',
success:function(response){
eval(response.responseText);
functionAssociatedWithButton();//Calling here the function associated with button
},
failure:function(){
return;
}
});
functionAssociatedWithButton();//Calling here the same function throws an error of function being undefined
問題在於使用Ajax加載的JS文件中存在的該函數-functionAssociatedWithButton()-可用並且僅在Ajax請求的成功函數中執行。
但是,如果我們嘗試在腳本的任何其他部分中訪問此函數,則JS引擎將引發錯誤-未定義functionAssociatedWithButton()。
在使用其余腳本的JS文件中,如何提供這樣的功能?
我嘗試使用此處建議的第4個選項-但這也無法解決問題。
任何人都可以對此發表一些看法。
提前致謝。
PS:完整的腳本寫在ExtJS的onReady函數中。 另外,考慮到在其他地方調用time函數可能未加載Ajax的可能性,我嘗試了在Ajax完成加載后調用該函數的情況(使用isLoading()和setTimeOut()),即使Ajax已加載完成加載后,僅在Ajax的成功函數中才能識別該功能,而在腳本的其他任何地方都無法識別該功能。
這與您創建的功能范圍有關。 該功能僅在success
功能中可用; 您實際上會遇到以下情況:
function foo() {
function bar() {
window.alert("hello");
}
}
console.log(typeof foo); // function
console.log(typeof bar); // undefined
您可能有一個向其添加函數的全局名稱空間對象,例如:
var test = {};
function foo() {
test.bar = function () {
window.alert("hello");
}
}
console.log(typeof foo); // function
foo();
console.log(typeof test.bar); // function
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.