博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
跨域技术
阅读量:4325 次
发布时间:2019-06-06

本文共 2247 字,大约阅读时间需要 7 分钟。

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

你可能感兴趣的文章
eclipse没有server选项
查看>>
CRC码计算及校验原理的最通俗诠释
查看>>
QTcpSocket的连续发送数据和连续接收数据
查看>>
使用Gitbook来编写你的Api文档
查看>>
Python XML解析(转载)
查看>>
jquery扩展 $.fn
查看>>
tomcat 多实例的Sys V风格脚本
查看>>
程序员如何讲清楚技术方案
查看>>
MapReduce-实践1
查看>>
UVa 815 - Flooded!
查看>>
jQuery基础--选择器
查看>>
减小服务器负担,Apache启用mod_expires模块
查看>>
20.Mybatis之逆向工程
查看>>
mysql 中时间和日期函数应用
查看>>
自动化测试-selenium初始化Driver参考
查看>>
mybatis使用collection查询集合属性规则
查看>>
linux查看文件的编码格式的方法 set fileencoding PYTHON
查看>>
Git 问题:SSL certificate problem: self signed certificate
查看>>
安全测试
查看>>
作业代码
查看>>