跨浏览器的CORS

检测 XHR 是否支持 CORS 的最简单方式,就是检查是否存在withCredentials属性。
再结合检测 XDomainRequest 对象是否存在,就可以兼顾所有浏览器了。

  function createCORSRequest(method, url) {
      var xhr = new XMLHttpRequest();
      if ("withCredentials" in xhr) {
        xhr.open(method, url, true)
      } else if (typeof XDomainRequest != "undefined") {
        vxhr = new XDomainRequest();
        xhr.open(method, url)
      } else {
        xhr = null
      }
      return xhr
    }

    var request = createCORSRequest("get", "http://www.baidu.com")
    if (request) {
      request.onload = function () {
        // 对request.responseText进行处理
      }
      request.send()
    }

 

FirefoxSafari Chrome 中的 XMLHttpRequest 对象与 IE 中的 XDomainRequest 对象类似,都
提供了够用的接口,因此以上模式还是相当有用的。这两个对象共同的属性/方法如下。
abort():用于停止正在进行的请求。
onerror:用于替代 onreadystatechange 检测错误。
onload:用于替代 onreadystatechange 检测成功。
responseText:用于取得响应内容。
send():用于发送请求。
以上成员都包含在 createCORSRequest()函数返回的对象中,在所有浏览器中都能正常使用。

原文地址:https://www.cnblogs.com/shengnan-2017/p/9408168.html