CORS,即Cross-Origin Resource Sharing (CORS) 是W3C草案拟定的浏览器与服务端如何进行跨域请求的方式,其原理是用自定义HTTP头来让浏览器和SERVER决定request、response的成功或失败。目前支持的浏览器有(Internet Explorer 8+, Firefox 3.5+, Safari 4+, and Chrome)。

对于CORS,Chrome、FireFox以及Safari,需要使用XmlHttpRequest2对象;而对于IE,则需要使用XDomainRequest;Opera目前还不支持这一特性,但很快就会支持。

因此,在对象的创建上,我们不得不首先针对不同的浏览器而进行一下预处理:

function createCORSRequest(method, url) {
  var xhr = new XMLHttpRequest();
  if ("withCredentials" in xhr) {

    // "withCredentials"属性是XMLHTTPRequest2中独有的
    xhr.open(method, url, true);

  } else if (typeof XDomainRequest != "undefined") {

    // 检测是否XDomainRequest可用
    xhr = new XDomainRequest();
    xhr.open(method, url);

  } else {

    // 看起来CORS根本不被支持
    xhr = null;

  }
  return xhr;
}

prettyprintjsundefined

事件处理:

原先的XmlHttpRequest对象仅仅只有一个事件——onreadystatechange,用以通知所有的事件,而现在,我们除了这个事件之外又多了很多新的。

事件 说明

onloadstart*	当请求发生时触发
onprogress	读取及发送数据时触发
onabort*	当请求被中止时触发,如使用abort()方法
onerror	当请求失败时触发
onload	当请求成功时触发
ontimeout	当调用者设定的超时时间已过而仍未成功时触发
onloadend*	请求结束时触发(无论成功与否)
注:带星号的表示IE的XDomainRequest仍不支持。

数据来自http://www.w3.org/TR/XMLHttpRequest2/#events。

下面是一个简单demo的代码:


function createCORSRequest(method, url) {
	  var xhr = new XMLHttpRequest();
	  if ("withCredentials" in xhr) {
	    // 针对Chrome/Safari/Firefox.
	    xhr.open(method, url, true);
	  } else if (typeof XDomainRequest != "undefined") {
	    // 针对IE
	    xhr = new XDomainRequest();
	    xhr.open(method, url);
	  } else {
	    // 不支持CORS
	    xhr = null;
	  }
	  return xhr;
	}
	function loadMessage(){
		var url ="http://xiaosan.me/ajax/ajax.php";
		var xhr = createCORSRequest('GET', url);
		xhr.onprogress = function(a){
			//console.log(a)
			document.getElementById("show").innerHTML = "请求中...";
		}
		xhr.onloadstart = function(){
			document.getElementById("show").innerHTML = "开始请求";
		}
		xhr.onreadystatechange = function(a){
			console.log(a);
		}
		xhr.onload = function(){
			var text = xhr.responseText;
			document.getElementById("show").innerHTML = text;
		}
		xhr.onerror = function(){
			alert("error");
		}
		xhr.send();
	}

DEMO地址:http://ouyo.info/lab/cors/ajax.html


接下来是服务端配置

http://enable-cors.org/ 这个网站列出了目前比较流行的服务端配置方法,现在拿php为例,最简单的方法是直接在php输出时设置:


header("Access-Control-Allow-Origin: *");

上面demo的服务端代码:

<?php
    header("Access-Control-Allow-Origin: *");
	echo "跨域请求成功";
?>

了解更多请移步:http://newhtml.net/using-cors/