HTML5:使用postMessage实现Ajax跨域请求

来源:互联网 发布:centos搭建php网站 编辑:程序博客网 时间:2024/05/29 17:03

HTML5:使用postMessage实现Ajax跨域请求

笔记2。

由于同源策略的限制,Javascript存在跨域通信的问题,典型的跨域问题有iframe与父级的通信等。

常规的几种解决方法:
(1) document.domain+iframe; (2) 动态创建script; (3) iframe+location.hash; (4) flash。

这里不细说这几种方法,记录的是HTML5的window.postMessage。postMessage兼容IE8+、Firefox、Opera、Safari、Chrome

需要两个异域的服务器来做测试,当然也可以用本地和线上服务器作为两个异域的服务器。假如使用phonegap开发,就可以将请求文件安装在客户端,然后动态请求服务器的数据处理,获得并显示数据。这样就可以用任意Web开发语言及方法来开发phonegap App所需的后台。

1.  postMessage的用法

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

假设有结构如下:

test.html<section id="wrapper">  <header>    <h1>postMessage (跨域)</h1>  </header>  <article>    <form>      <p>        <label for="message">给iframe发一个信息:</label>        <input type="text" name="message" value="son" id="message" />        <input type="submit" />      </p>    </form>    <h4>目标iframe传来的信息:</h4>    <p id="test">暂无信息</p>    <iframe id="iframe"    src="http://xiebiji.com/works/postmessage/iframe.html"></iframe>  </article></section>
iframe.html<strong>iframe指向xiebiji.com</strong><form>  <p>    <label for="message">给父窗口发个信息:</label>    <input type="text" name="message" value="dad" id="message" />    <input type="submit" />  </p></form><p id="test">暂无信息。</p>

下面是test.html里的Javascript代码(发送数据):

var win = document.getElementById("iframe").contentWindow;document.querySelector('form').onsubmit=function(e){  win.postMessage(document.getElementById("message").value,"*");  if (e.preventDefault)    e.preventDefault();  e.returnValue = false;}

关键代码就一句:

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

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

然后是iframe.html里侦听接收数据的代码:

var parentwin = window.parent;window.onmessage=function(e){  document.getElementById("test").innerHTML = e.origin + "say:" + e.data;  parentwin.postMessage('HI!你给我发了"<span>'+e.data+'"</span>。',"*");};

很简单,相信一看就懂了。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请求。其实是很简单的东西。

贴个示例代码吧,但跟以上的代码无关。

(function(){  //获取跨域数据  window.onmessage = function(e){    var url = "http://yangzebo.com/demo/noforget/test.php?msg=" + e.data;    //Ajax    var xhr = getXHR();    if(xhr){      xhr.open("GET",url,true);      xhr.onreadystatechange = changeHandle;      xhr.send(null);    }else{     alert("不支持Ajax");    }    function changeHandle(){//返回处理      if(xhr.readyState == 4){        var parentwin = window.parent;        parentwin.postMessage(xhr.responseText,"*");//跨域发送数据      }    }    function getXHR(){//获取XMLHttpRequest      var xhr_temp;      if(window.XMLHttpRequest){        xhr_temp = new XMLHttpRequest();      }else if(window.ActiveXObject){        xhr_temp = new ActiveXObject("Microsoft.XMLHTTP");      }else{        xhr_temp = null;      }      return xhr_temp;    }  };})();

然后给个不好看的Demo。

有兴趣代码请求啥的自个用开发人员工具看吧,“zebo男”是从数据库读出来的,“my msg”是sendAndReceive.html发给test.php的Ajax请求的参数,通过test.php和iframeforAjax.html回传到sendAndReceive.html。

3. 提示

要获取iframe的contentWindow才能调用postMessage。

postMessage一定要在iframe加载完成之后调用才可以正常运行。(这个耗了我好长时间)

最后要感谢Joe哥的提示和给我偷用服务器来测试的hulin小妹妹。:D