XMLHttpRequest 2版本允许向不同域名的服务器发出HTTP请求。使用跨域资源共享的前提是:浏览器必须支持这个功能,且服务器端必须同意这种跨域。如果能够满足上面两个条件,则代码的写法与不跨域的请求完全一样。例如:
var xhr = createXHR();
var url = 'http://other.server/and/path/to/script'; // 请求的跨域文件
xhr.open('GET', url, true);
xhr.onreadystatechange = function (){
if ( xhr.readyState == 4 && xhr.status == 200 ){
console.log(xhr.responseText);
}
}
xhr.send();