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加载完成之后调用才可以正常运行。(这个耗了我好长时间)