gpt4 book ai didi

javascript - Mootools Request.HTML 返回未定义

转载 作者:太空宇宙 更新时间:2023-11-04 16:15:10 24 4
gpt4 key购买 nike

我在应用程序的脚本部分 (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);

最佳答案

您应该考虑两件事。一是可能存在 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);
});

关于javascript - Mootools Request.HTML 返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41134379/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com