1.CORS
Firefox3.5+、Safari4+、Chrome、iOS版Safari和Android平台中的WebKit都通过XMLHttpRequest对象实现对CORS原生支持。IE则是引入XDR类型(与XHR类似)来支持CORS。
XHR跨域:
跨域注意:1.不能使用setRequestHeader()设置自定义头部
2.不能发送接收cookie
3.调用getAllResponseHeaders()总会返回空字符串
function createXHR(){
var xhr;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
xhr = new ActiveXObject('Micosoft.XMLHTTP');
}
return xhr;
}
var xhr = createXHR();
xhr.onreadystatechange = function(){
if(xhr.readyState==4){
try{
if((xhr.status == 200 && xhr.status < 300) || xhr.status == 304){
console.log(xhr.status, xhr.responseText);
console.log(xhr.getAllResponseHeaders());
}else{
console.log("unsuccessful:" + xhr.status + xhr.statusText);
}
}catch(ex){
xhr.ontimeout();
}
}
};
xhr.timeout = 1000;
xhr.ontimeout = function(){
console.log("timeout");
}
xhr.open("get", "http://www.somewhere-else.com/page/", true);
xhr.send();
XDR实现跨域:
var xdr = new XDomainRequest();
xdr.onload = function(){
alert(xdr.responseText);
};
//xdr出现错误时,不能收到具体错误,只能检测到存在错误
//导致xdr出错的原因很多,onerror函数是必不可少的
xdr.onerror = function(){
alert("an error occurred");
}
//xdr的open函数只接受两个参数,只能异步执行
xdr.open("get","http://www.somewhere-else.com/page/");
xdr.send();
XDR的post请求:
xdr.open("post","http://www.somewhere-else.com/page/");
xdr.contentType = "application/x-www-form-urlencoded";
xdr.send("name=value1&pass=value2");