IE9下解决浏览器跨域问题


众所周知,我们在开发中,经常会遇到跨域的问题,我们处理跨域的方案也有很多
1、 JsonP
2、 CORS
3、 Domain + Ifram
4、 Nginx
5、 PostMessage
6、 NodeJS中间件代理跨域
7、 Websocket协议跨域
8、 Location.hash + Ifram
9、 window.name + Ifram
等等以上方案。

今天我们要分享的是,IE9下,CORS不能解决跨域的情况下,如何处理跨域请求。

// 兼容IE9 CORS下POST请求被拒绝
  function getVerification_ie9(param) {
    jQuery.support.cors = true;
    $.ajax({
      url: window.protocol_online + '//' + window.hostname_online + '/remixed/service_admin_platform/sendValidCode',
      type: "post",
      headers: { 'Content-Type': 'application/json;charset=UTF-8' },
      dataType: "JSON",
      data: JSON.stringify({
        'telephone': param
      }),
      success: function (data) { },
      error: function () {
        toastShow('获取证码失败!')
      }
    });
  }
// 兼容IE9 CORS下POST请求被拒绝
  function sendUserInfo_ie9() {
    var tel = document.getElementById('telNumber').value;
    var verificationCode = document.getElementById('verificationCode').value
    var userName = document.getElementById('userName').value;
    var city = document.getElementById('city').value;
    var obj = JSON.stringify({
      'telephone': tel,
      'validCode': verificationCode,
      'name': userName,
      'address': city
    })
    jQuery.support.cors = true;
    $.ajax({
      url: window.protocol_online + '//' + window.hostname_online + '/remixed/service_admin_platform/saveCustomerInfo',
      type: "post",
      headers: { 'Content-Type': 'application/json;charset=UTF-8' },
      dataType: "JSON",
      data: obj,
      success: function (data) {
        if (data.code == 100) {
          document.getElementsByClassName('getting-information')[0].style.display = "none";
          document.getElementsByClassName('success-confirm')[0].style.display = "block";
          if (data.data) {
            document.getElementById('name').innerHTML = data.data;
          }
        } else if (data.code == 102) { // 预约试听体验课失败!
          toastShow(data.message || '验证码错误~')
        }
      },
      error: function () {
        toastShow('预约信息提交失败!')
      }
    });
  }

如上所述,最关键的地方想必大家应该也注意到啦。
jQuery.support.cors = true;

还有一种方案依然可以解决这类情况,
就是放弃用XMLHttpRequest对象,转而使用IE低版本支持的XDomainRequest对象。

下面用代码实现一下这种解决方案

function fetchIe9(url, options = {}){
  if (window.XDomainRequest) {
    return new Promise((resolve, reject) => {
      const method = options.method || 'GET';
      const timeout = options.timeout || 30000;
      let data = options.body || options.params || {};
      if (data instanceof Object) {
        data = JSON.stringify(data);
      }
      const XDR = new XDomainRequest();
      XDR.open(method, url);
      XDR.timeout = timeout;
      XDR.onload = () => {
        try {
          const json = JSON.parse(XDR.responseText);
          return resolve(json.data);
        } catch (e) {
          reject(e);
        }
        return reject({});
      };

      // fix random aborting: https://cypressnorth.com/programming/internet-explorer-aborting-ajax-requests-fixed/

      XDR.onprogress = () => {};
      XDR.ontimeout = () => reject('XDomainRequest timeout');
      XDR.onerror = () => reject('XDomainRequest error');
      setTimeout(() => {
        XDR.send(data);
      }, 0);
    });
  } else {
    // native fetch or polyfill fetch(XMLHttpRequest)
    // fetch...
  }
}

该问题是我在前半年实现我们部门的官网时,遇到的较为棘手的一个问题。但是本着不抛弃不放弃一个用户的原则,进行了这些困难的攻坚。
祝大家生活愉快

声明:Xuhao's Blog|版权所有,违者必究|如未注明,均为原创|本网站采用BY-NC-SA协议进行授权

转载:转载请注明原文链接 - IE9下解决浏览器跨域问题


Carpe Diem and Do what I like