2016-12-14 41 views
1

我在應用程序的腳本部分中動態加載Mootools(AutoWWW),因爲它不允許直接使用HTML。Mootools Request.HTML返回undefined

我正在使用Request.HTML並希望獲取頁面的html,但它返回一個'undefined'消息。我怎樣才能解決這個問題?

我的代碼:

function loadScript(url, callback) { 
    // Adding the script tag to the head as suggested before 
    var head = document.getElementsByTagName('head')[0]; 
    var script = document.createElement('script'); 
    script.type = 'text/javascript'; 
    script.src = url; 

    // Then bind the event to the callback function. 
    // There are several events for cross browser compatibility. 
    script.onreadystatechange = callback; 
    script.onload = callback; 

    // Fire the loading 
    head.appendChild(script); 
} 

var mootools = new Request({ 
    url: 'http://google.com', 
    method: 'get', 
    onSuccess: function(responseText){ 
     alert(responseText); 
    } 
}); 

loadScript("https://ajax.googleapis.com/ajax/libs/mootools/1.6.0/mootools.min.js", mootools); 
+0

不知道正是你正在嘗試做的,你能解釋一下更好?對我來說,看起來你正試圖在MooTools庫加載前從MooTools的方法加載MooTools庫,它不是CDN的MooTools網站。 – Sergio

+0

我剛剛編輯我的帖子,並更改請求的網址,因爲它很混亂,我已經將它設置到主頁來測試。基本上我想通過GET返回像google.com這樣的網址的HTML,並將其顯示在警報中。 loadScript函數不是mootools,函數應該工作並加載mootools.min.js,然後調用使用庫運行GET請求的mootools回調函數。 – zeddex

回答

1

有你應該考慮兩件事情。一個是可能的CORS限制,另一個是當你做head.appendChild(script);時它會異步加載腳本。

這意味着MooTools將被加載,但在調用callback函數之前它將不可用。要解決這個問題,您應該在loadScript函數內部進行回調,並在該回調函數內部調用作爲函數參數傳遞的另一個回調函數。

function loadScript(url, callback) { 
 
    // Adding the script tag to the head as suggested before 
 
    var head = document.getElementsByTagName('head')[0]; 
 
    var script = document.createElement('script'); 
 
    script.type = 'text/javascript'; 
 

 
    script.onreadystatechange = callback; 
 
    script.onload = function() { 
 
    new Request({ 
 
     url: 'https://jsonplaceholder.typicode.com/posts/1', 
 
     method: 'get', 
 
     onSuccess: callback 
 
    }).send(); 
 
    }; 
 
    script.src = url; 
 

 
    head.appendChild(script); 
 
} 
 

 
loadScript("https://ajax.googleapis.com/ajax/libs/mootools/1.6.0/mootools.min.js", function(text) { 
 
    alert(text); 
 
});

+0

感謝這個工程,只是想知道除了json請求之外運行更多mootools函數的最佳做法是什麼?例如,如果我想調用一個函數POST,也就是函數被打包到另一個函數中,並且回調有點令人困惑。 – zeddex

+0

@zeddex在你傳遞給你的loadScript函數的回調函數中你可以添加MooTools代碼,在那裏添加MooTools頁面。因此,將示例中的警報替換爲MooTools代碼。 – Sergio