Mootools Request.HTML returns 未定义

Mootools Request.HTML returns undefined

我正在应用程序 (AutoWWW) 的脚本部分动态加载 Mootools,因为它不允许直接 HTML 使用。

我正在使用 Request.HTML 并且想要获取页面的 html 但它 returns 是 '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);

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