我在应用程序的脚本部分(AutoWWW)中动态加载Mootools,因为它不允许直接使用HTML。
我正在使用Request.HTML并希望获取页面的html但它返回“未定义”消息。我该如何解决这个问题?
我的代码:
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 :(得分: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);
});