解决ajax跨域请求 (总结)


ajax跨域请求,目前已用几种方法实现:   1)用原生js的xhr对象实现。                var url="http://freegeoip.net/json/";
              
               //创建xhr对象
               function createCORSXhr(url,method){
                    var xhr=new XMLHttpRequest();
                    if("withCredentials" in xhr){
                              xhr.open(method,url,true);
                         }else if(typeof XDomainRequest !=="undefined"){
                              xhr=new XDomainRequest();
                              xhr.open(method,url);    
                         }else
                              xhr=null;
                         return xhr;                        
                    }
                   
               //创建ajax请求,支持跨域
               function sendAjaxRequest(){
                    var xhr=createCORSXhr(url,"get");
                    xhr.onload=function(){
                         if(xhr.readyState==4){
                         if(xhr.status>=200 && xhr.status<300 || xhr.status==304){
                              alert(xhr.responseText);
                              }else{
                                   alert(" ajax error...")
                                   }
                         }
                    };
                    xhr.onerror=function(){
                         alert("error code:"+xhr.status)
                    }
                    xhr.send(null);
                    };

               sendAjaxRequest()
  这种方式需要获取相应对象的支持,对于IE,则是XDomainRequest,此种方式cookie不会参与传递。该方式应用了CORS(跨域资源共享)技术,说到底,就是在请求头和响应头中做手脚。在请求头中,加上Origin:协议+域名+端口,当然也可以Origin:null。在响应头中,服务端返回Access-control-Allow-Origin:*.   2),通过jsonp数据来实现,说白了,jsonp就是js可执行文件由于