HTML5 AJAX跨域请求

方法一:HTML5新的标准中,增加了” Cross-Origin Resource Sharing”特性,这个特性的出现使得跨域通信只需通过配置http协议头来即可解决。


Cross-Origin Resource Sharing 详细解释见:
http://dvcs.w3.org/hg/cors/raw-file/tip/Overview.html

Cross-Origin Resource Sharing实现的最重要的一点就是对参数” Access-Control-Allow-Origin”的配置,即通过 次参数检查该跨域请求是否可以被通过。
如:Access-Control-Allow-Origin:http://a.com表示允许a.com下的域名跨域访问;
Access-Control-Allow-Origin:*表示允许所有的域名跨域访问。


如果需要读取读取cookie:
需要配置参数:Access-Control-Allow-Credentials:true
同时在xhr发起请求的时候设置参数withCredentials为true:
var xhr = new XMLHttpRequest();
xhr.open();
xhr.withCredentials = true; //这个放在xhr.open后面执行,否则有些浏览器部分版本会异常,导致设置无效。

示例代码:
php:

php
1
2
3
4
header('Access-Control-Allow-Origin:http: //a.com');
header('Access-Control-Allow-Methods:POST,GET');
header('Access-Control-Allow-Credentials:true'); 
echo'Cross-domain Ajax';

JS:

JavaScript

1
2
3
4
5
6
7
8
9
10
varxhr =newXMLHttpRequest(); ; 
xhr.open('GET','http: //b.com/cros/ajax.php',true);
xhr.withCredentials =true;
xhr.onload =function() {          
  alert(xhr.response);//reposHTML;
};  
xhr.onerror =function() {
 alert('error making the request.');
};
xhr.send();

方法二:使用postMessage实现Ajax跨域请求

1.  postMessage的用法

postMessage是HTML5为解决js跨域问题而引入的新的API,允许多个iframe/window跨域通信。

假设有结构如下:

test.html

Js代码   收藏代码
  1. <section id="wrapper">  
  2.   <header>  
  3.     <h1>postMessage (跨域)</h1>  
  4.   </header>  
  5.   <article>  
  6.     <form>  
  7.       <p>  
  8.         <label for="message">给iframe发一个信息:</label>  
  9.         <input type="text" name="message" value="son" id="message" />  
  10.         <input type="submit" />  
  11.       </p>  
  12.     </form>  
  13.     <h4>目标iframe传来的信息:</h4>  
  14.     <p id="test">暂无信息</p>  
  15.     <iframe id="iframe"  
  16.     src="http://xiebiji.com/works/postmessage/iframe.html"></iframe>  
  17.   </article>  
  18. </section>  


  

iframe.html
Js代码   收藏代码
  1. <strong>iframe指向xiebiji.com</strong>  
  2. <form>  
  3.   <p>  
  4.     <label for="message">给父窗口发个信息:</label>  
  5.     <input type="text" name="message" value="dad" id="message" />  
  6.     <input type="submit" />  
  7.   </p>  
  8. </form>  
  9. <p id="test">暂无信息。</p>  

下面是test.html里的Javascript代码(发送数据):
Js代码   收藏代码
  1. var win = document.getElementById("iframe").contentWindow;  
  2. document.querySelector('form').οnsubmit=function(e){  
  3.   win.postMessage(document.getElementById("message").value,"*");  
  4.   if (e.preventDefault)  
  5.     e.preventDefault();  
  6.   e.returnValue = false;  
  7. }  



  关键代码就一句:

win.postMessage(document.getElementById("message").value,"*");

  postMessage是通信对象的一个方法,所以向iframe通信,就是iframe对象调用postMessage方法。postMessage有两个参数,缺一不可。第一个参数是要传递的数据,第二个参数是允许通信的域,“*”代表不对访问的域进行判断,可理解为允许所有域的通信。

  然后是iframe.html里侦听接收数据的代码:
Js代码   收藏代码
  1. var parentwin = window.parent;  
  2. window.onmessage=function(e){  
  3.   document.getElementById("test").innerHTML = e.origin + "say:" + e.data;  
  4.   parentwin.postMessage('HI!你给我发了"<span>'+e.data+'"</span>。',"*");  
  5. };  


  很简单,相信一看就懂了。e.data包含传送过来的数据,e.origin指代源域。

然后iframe.html也给test.html发送回应的数据,test.html接收数据。代码雷同,就不贴代码了。

点此查看Demo(代码素Joe哥给的)
2. Ajax跨域请求

基于以上的跨域通信,只要将Ajax代码放在iframe.html里的onmessage处理函数里头,将test.html用postMessage传过来的数据作为参数发送请求,再将返回的数据用postMessage传给test.html。这样就实现了跨域的Ajax请求。其实是很简单的东西。

贴个示例代码吧,但跟以上的代码无关。
Js代码   收藏代码
  1. (function(){  
  2.   //获取跨域数据  
  3.   window.onmessage = function(e){  
  4.     var url = "http://yangzebo.com/demo/noforget/test.php?msg=" + e.data;  
  5.     //Ajax  
  6.     var xhr = getXHR();  
  7.     if(xhr){  
  8.       xhr.open("GET",url,true);  
  9.       xhr.onreadystatechange = changeHandle;  
  10.       xhr.send(null);  
  11.     }else{  
  12.      alert("不支持Ajax");  
  13.     }  
  14.     function changeHandle(){//返回处理  
  15.       if(xhr.readyState == 4){  
  16.         var parentwin = window.parent;  
  17.         parentwin.postMessage(xhr.responseText,"*");//跨域发送数据  
  18.       }  
  19.     }  
  20.     function getXHR(){//获取XMLHttpRequest  
  21.       var xhr_temp;  
  22.       if(window.XMLHttpRequest){  
  23.         xhr_temp = new XMLHttpRequest();  
  24.       }else if(window.ActiveXObject){  
  25.         xhr_temp = new ActiveXObject("Microsoft.XMLHTTP");  
  26.       }else{  
  27.         xhr_temp = null;  
  28.       }  
  29.       return xhr_temp;  
  30.     }  
  31.   };  
  32. })(); 

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值