1

我已经四处寻找解释,以便我能够理解上述功能。我遇到的情况是在 Google Maps API 文档中:

function downloadUrl(url, callback) {
  var request = window.ActiveXObject ?
      new ActiveXObject('Microsoft.XMLHTTP') :
      new XMLHttpRequest;

  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      request.onreadystatechange = doNothing;
      callback(request.responseText, request.status);
    }
  };

  request.open('GET', url, true);
  request.send(null);
}

function doNothing() {}

如果有人可以提供一些启示,将不胜感激。

4

2 回答 2

2
function downloadUrl(url, callback) { // pass a URL and a function to call on success
  var request = window.ActiveXObject ?
      new ActiveXObject('Microsoft.XMLHTTP') :
      new XMLHttpRequest; // create an xmlhttprequest, native if possible, activeX for older IE - the construct is a ternary conditional statement
  // set up handling of the state change, we only want the 4th
  request.onreadystatechange = function() { // when the request changes state 
                                            // i.e from sending to having received
    if (request.readyState == 4) { // request done
      request.onreadystatechange = doNothing; // removed this anonymous function on 4th state (done)
      callback(request.responseText, request.status); // call the supplied function with result
    }
  };

  request.open('GET', url, true); // now initialize
  request.send(null); // now execute
}

更新:这些天(2018 年 7 月)比 activeX 更有可能找到 XMLHttpRequest,因此建议使用以下任何一种:

  • 切换测试,
  • 删除对 activeX 的测试,
  • 添加一个 try/catch 或
  • 使用Fetch
于 2013-04-09T16:32:01.367 回答
0

此代码使用浏览器中的 AJAX 功能来获取 URL 的内容。

于 2013-04-09T16:28:07.807 回答