第一种 CORS
服务器设置头标 :设置Access-Control-Allow-Origin
Access-Control-Allow-Origin: http://blog.youkuaiyun.com
浏览器,操作类似普通 XHR:
var xhr = new XMLHttpRequest();
xhr.open("GET", "/hfahe", true);
xhr.send();
完整浏览器端:
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// 此时即支持CORS的情况
// 检查XMLHttpRequest对象是否有“withCredentials”属性
// “withCredentials”仅存在于XMLHTTPRequest2对象里
xhr.open(method, url, true);
} else if (typeof!= "undefined") {
// 否则检查是否支持XDomainRequest,IE8和IE9支持
// XDomainRequest仅存在于IE中,是IE用于支持CORS请求的方式
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// 否则,浏览器不支持CORS
xhr = null;
}
return xhr;
}
var xhr = createCORSRequest('GET', url);
if (!xhr) {
throw new Error('CORS not supported');
}
CORS与JSONP相比,更为先进、方便和可靠。
1、 JSONP只能实现GET请求,而CORS支持所有类型的HTTP请求。
2、 使用CORS,开发者可以使用普通的XMLHttpRequest发起请求和获得数据,比起JSONP有更好的错误处理。
3、 JSONP主要被老的浏览器支持,它们往往不支持CORS,而绝大多数现代浏览器都已经支持了CORS(这部分会在后文浏览器支持部分介绍)。
第二种 图像 ping
用 img 标签可以加在任何其他网页上的内容,没有跨域的限制。(埋点和谷歌统计的方式、广告跟踪浏览量)
var img = new Image();
img.obload = img.onerror = function(){
alert("done.");
}
img.src = "htp://wwww.test.com?name=zhangxue";
缺点: 只能发送 get 请求, 不能访问服务区返回的响应内容。
第三种 JSONP
利用 script 标签的 src 不受跨域的限制,
优点:可以访问服务器返回响应的内容,支持浏览器和服务器之间的双向通信。
缺点:如果其他域是不安全的,返回内容夹杂恶意代码;难以确定 JSONP 请求是否失败,使用计时器定时检测
var scriot = document.createElement("script");
script.src ="htttp://www.test.com?callback=handleRes"
document.body.insertBefore(script, document.body.firstChild);
第四种 websocket
不受跨域限制