【问题标题】:XMLHttpRequest.onreadystatechange vs. addEventListenerXMLHttpRequest.onreadystatechange 与 addEventListener
【发布时间】:2016-04-26 15:22:11
【问题描述】:

阅读 XMLHttpRequest 以在 Google Chrome 扩展中使用,我遇到了一个问题。

MDN specifies usingXMLHttpRequest.addEventListener,而Google usesXMLHttpRequest.onreadystatechange 在他们的例子中。

在向 Google Apps 脚本发出 GET 请求时,这两种方法之间是否存在偏好?我是异步 Javascript 的新手,在此之前我一直在 GAS 工作。

【问题讨论】:

    标签: google-chrome-extension google-apps-script xmlhttprequest


    【解决方案1】:

    首选是浏览器兼容性。来自 MSN 上的 XMLHttpRequest API 文档。

    https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#Properties

    所有浏览器都支持onreadystatechange 作为XMLHttpRequest 实例的属性。

    https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#Events

    除了将 on* 属性设置为处理函数之外,包括 Firefox 在内的最新浏览器还支持通过标准 addEventListener API 侦听 XMLHttpRequest 事件。

    由于 Apps Script Web Apps 很快将只支持现代浏览器(因为本机和模拟模式已被弃用),您可以使用其中任何一种。

    【讨论】:

      【解决方案2】:

      onreadystatechange 触发太多,您可能不需要听它。请改用loadend(所有情况,包括失败/中止)、load(成功)、errorabort 事件。

      更多信息请参见https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

      【讨论】:

      • 你说得有道理。 onreadystatechange 会在每次状态更改时触发,但 addEventListener 会监听特定事件(loadendloaderrorabort)。
      【解决方案3】:

      此外,如果您可以控制浏览器类型/版本,则可以使用传递给 onreadystatechange 函数的对象进行 polyfill:

      var oReq = new XMLHttpRequest();
      // This part for modern browsers
      oReq.addEventListener("progress", updateProgress, false);
      oReq.addEventListener("load", transferComplete, false);
      oReq.addEventListener("error", transferFailed, false);
      oReq.addEventListener("abort", transferCanceled, false);
      // This part for old ones
      oReq.onreadystatechange = functionSwitch;
      

      functionSwitch 将调用正确的函数(将在 updateProgress、transferComplete 等之间进行选择)以避免重复代码。

      我见过有人在使用 Windows XP,但可能任何 addEventListener 都不起作用。看看:addEventListener Compatibility。我没有通过 addEventListener 找到特定的 xmlhttprequest 事件列表。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-09-16
        • 2022-07-16
        • 1970-01-01
        • 2012-02-18
        • 2023-03-03
        • 2017-02-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多