ajax 跨域问题之Iframe
iframe方式来解决ajax+php跨域问题
1.首先呢?什么是跨域,域就是域名,就是在一个域名下调用另一个域名下的ajax获取数据
举例说明:
aa.webv9.com
bb.webv9.com
aa.webv9.com 下调用bb.webv9.com ajax方法获取数据
如果你直接用ajax方式从http://bb.webv9.com/ajax/ky/test.php获取数据在IE下面会提示没有权限
FF下没有提示,但也不执行,原因就是javascript ajax 安全性问题。
2.解决跨域的前提条件
必须能同时操作这两个网站,也就是说这两个网站都是你做。
3.思路
1.aa.webv9.com 网站要调用bb.webv9.com网站下的ajax获取数据 例如 index.html
2.bb.webv9.com 网站目录下必有个ajax请求网页 例如:domain.html
3.设置aa.webv9.com/index.html 和 bb.webv9.com/domain.html的
document.domain 属性相同域名 例如: document.domain="webv9.com";
4.aa.webv9.com 利用iframe的src属性 加载 http://bb.webv9.com/domain.html
5.加载以后iframe就可以请求到http://bb.webv9.com/domain.html的ajax方法了
6.iframe获取到数据以后通过回调函数传递给aa.webv9.com页面
4.贴实例代码
在本地设置两个域名测试用
aa.webv9.com
bb.webv9.com
目录文件
bb.webv9.com/ajax/
test.php
<?php echo 'test'; ?>
domain.html
1 <html>
2 <body>
3 <h1>domian.html</h1>
4 <script>
5 var content='';
6 document.domain="webv9.com";
7 function sendRequest(url,func){
8 var data=false;
9 var ajax=new XMLHttpRequest;
10 ajax.open('get',url);
11 ajax.send(null);
12 ajax.onreadystatechange=function(){
13 if(ajax.readyState==4){
14 if(ajax.status==200){
15 func(ajax.responseText); //func是回调函数
16 }
17 }
18
19 }
20 }
21 </script>
22 </body>
23 </html
aa.webv9.com/ajax/ky/
index.html
<iframe src="http://bb.webv9.com/ajax/domain.html" name="ajaxIframe"></iframe>
<button onclick="callRequest()">click</button>
<script>
document.domain="webv9.com";
function callRequest(){
callSubRequest();
}
function callSubRequest(){
ajaxIframe.window.sendRequest('http://bb.webv9.com/ajax/test.php',tt);
}
//处理iframe ajax请求的回调函数
function tt(data){
alert('晕哦'+data);
}
</script>
浙公网安备 33010602011771号