跨域问题,网上资料很多,但是太多复制粘贴,还错误百出,这里我总得说一下吧
- 第一个方法就是jsonp,这个只能采用get方式请求,具体自己百度,由于post用的多,我不喜欢这个方法,直接淘汰
- 第二个方法就是cros跨域,服务端要设置响应头如下
注意header("Access-Control-Allow-Credentials", true) header("Access-Control-Allow-Origin", request.getHeader("Origin"))
"Access-Control-Allow-Origin"不能设置成"*"
function createCORSRequest(method,url){
var xhr=new XMLHttpRequest();
if("withCredentials" in xhr){
xhr.open(method,url,true);
}else if(typeof XDomainRequest != "undefined"){//IE10之前的版本使用XDmainRequest支持CORS
xhr=new XDomainRequest();
xhr.open(method,url);
}else{
xhr=null;
}
xhr.withCredentials = true;
return xhr;
}
var request=createCORSRequest("post","请求的url");
if(request){
request.onload=function(data){
alert(data);
};
request.send();
}
其中 xhr.withCredentials = true; 是跨域关键
如果用jquery写的话就比较简单了
$.ajax({
type : "post",
url : "请求的url",
dataType:"json",
xhrFields: {
withCredentials:true
},
success : function(msg){
alert(msg.ret);
}
});
如果要携带cookie的话,cookie设置成主域名,就可以携带了,当然这是在主域名相同的情况下,二级域名之间的跨域才可以传递cookie
这里我要强调一下用jquery写的话虽然简单,但是要注意jquery插件版本,如果是低版本或者min版本,有可能会不支持这种cros跨域,博主1.7.3的可以用,我曾经就因为用的低版本的min版本,怎么也成功不了,希望猿友们少走点弯路!