ie10兼容ajax withCredentials

本次需求用到ajax请求,又要兼容ie10;
由于存在跨域问题,需要加上 withCredentials: true

$.ajax({
      url: `//XXXXXXXX/cet-refund/process`,
      type: 'get',
      xhrFields: {
        withCredentials: true,
      },
      crossDomain: true,
      data: data
      
    })

但是ie10下一只报错 。


image.png

换成axios接口正常,虽然解决了问题。但是要找一下原因。
网上查询之后,查看公司封装的代码发现了问题;

原来,在IE10环境下,withCredentials 属性必须在open方法成功执行之后,send执行之前设置才可以,否则会报错。如果open方法执行失败了,设置 withCredentials 属性依然会报错。

      // if (settings.xhrFields) for (name in settings.xhrFields) xhr[name] = settings.xhrFields[name]
        var async = 'async' in settings ? settings.async : true
        xhr.open(settings.type, settings.url, async, settings.username, settings.password)
        
        if (settings.xhrFields) for (name in settings.xhrFields) xhr[name] = settings.xhrFields[name] // 这一行原来在上面

        for (name in headers) nativeSetHeader.apply(xhr, headers[name])
  
        if (settings.timeout > 0) abortTimeout = setTimeout(function(){
            xhr.onreadystatechange = empty
            xhr.abort()
            ajaxError(null, 'timeout', xhr, settings, deferred)
        }, settings.timeout)
  
        // avoid sending empty string (#319)
        xhr.send(settings.data ? settings.data : null)

之后接口就通了

参考:https://blog.csdn.net/weixin_33725270/article/details/89025975

你可能感兴趣的:(ie10兼容ajax withCredentials)