跨域请求一直是网页编程中的一个难题,在过去,绝大多数人都倾向于使用JSONP来解决这一问题。不过现在,我们可以考虑一下W3C中一项新的特性——CORS(Cross-Origin Resource Sharing)了。
客户端
创建XmlHttpRequest对象
对于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;
}
var xhr = createCORSRequest('GET', url);
if (!xhr) {
throw new Error('CORS not supported');
}
事件处理
原先的XmlHttpRequest对象仅仅只有一个事件——onreadystatechange,用以通知所有的事件,而现在,我们除了这个事件之外又多了很多新的。
事件
说明
onloadstart*
当请求发生时触发
onprogress
读取及发送数据时触发
onabort*
当请求被中止时触发,如使用abort()方法
onerror
当请求失败时触发
onload
当请求成功时触发
ontimeout
当调用者设定的超时时间已过而仍未成功时触发
onloadend*
请求结束时触发(无论成功与否)
绝大多数情况下,我们只需要和onload及onerror打交道,就像下面这样:
xhr.onload = function() {
var responseText = xhr.responseText;
console.log(responseText);
// 继续其它代码
};
xhr.onerror = function() {
console.log('There was an error!');
};
这儿有一点小异样。尽管我们可以通过onerror得知请求发生了错误,但在事件处理时,我们无法从代码上获知失败的任何原因。比如,FireFox在失败时将response