跨域技术

1.CORS

使用自定义http头部让浏览器与服务器沟通,从而确定请求和响应是成功还是失败

IE浏览器

   支持XDomainRequest( )构造函数 只能实现异步功能,没有state属性,只能通过onload事件判定响应是否有效。

  特点:

     不能请求和发送cookie

     不能访问头部信息

     只能修改头部的content-type字段

     只支持post和get请求

   实现代码

var xdr = new XDomainRequest();
xdr.onload = function(){
    console.log(xdr.responseText);
}
xdr.open('get', url地址);
......
xdr.send(null);

其他浏览器支持

    XHTMLRequest()创建对象

    可以访问state和stateText属性,还支持同步请求

 特点:

     不能使用setRequeatheader()

     设置自定义头部

    不能发送和接受cookie

    调用getAllResponseHeader()方法总会返回空字符串

 实现代码

var xhr =  new XMLHttpRequest();
xhr.onreadystatechange = function () {
    if(xhr.readyState == 4){
        if(xhr.status >= 200 && xhr.status < 304 || xhr.status == 304){
            console.log(xhr.responseText);
        }
    }
}
xhr.open('get', url地址);
......
xhr.send(null);

跨浏览器的CORS

检查XHR是否存在withCredentials属性,再结合检测XDomainRequest对象是否存在

  实现代码

function createCORS(method, url){
    var xhr = new XMLHttpRequest();
    if('withCredentials' in xhr){
        xhr.open(method, url, true);
    }else if(typeof XDomainRequest != 'undefined'){
        var xhr = new XDomainRequest();
        xhr.open(method, url);
    }else{
        xhr = null;
    }
    return xhr;
}
var request = createCORS('get', url地址);
if(request){
    request.onload = function(){
        ......
    };
    request.send();
}

2.JSONP

由回调函数和数据组成,当响应到来时调用。 回调函数的名字一般在请求中指定,数据就是传入回调函数中的JSON数据 JSONP通过动态

实现代码

function handleResponse(response){
    console.log('The responsed data is: '+response.data);
}
var script = document.createElement('script');
script.src = 'http://www.baidu.com/json/?callback=handleResponse';
document.body.insertBefore(script, document.body.firstChild);

3.动态创建script                                

元素使用,使用时可以为src属性指定一个跨域URL。

实现代码

function loadScript(url, func) {
  var head = document.head || document.getElementByTagName('head')[0];
  var script = document.createElement('script');
  script.src = url;

  script.onload = script.onreadystatechange = function(){
    if(!this.readyState || this.readyState=='loaded' || this.readyState=='complete'){
      func();
      script.onload = script.onreadystatechange = null;
    }
  };

  head.insertBefore(script, 0);
}
window.baidu = {
  sug: function(data){
    console.log(data);
  }
}
loadScript('http://suggestion.baidu.com/su?wd=w',function(){console.log('loaded')});
原文地址:https://www.cnblogs.com/microcosm/p/6543359.html