系统城装机大师 - 固镇县祥瑞电脑科技销售部宣传站!

当前位置:首页 > 网络编程 > PHP编程 > 详细页面

PHP ajax跨子域的解决方案之document.domain+iframe实例分析

时间:2020-03-05来源:电脑系统城作者:电脑系统城

本文实例讲述了PHP ajax跨子域的解决方案之document.domain+iframe。分享给大家供大家参考,具体如下:

对于主域相同,子域不同,我们可以设置相同的document.domain来欺骗浏览器,达到跨子域的效果。

例如:我们有两个域名:www.a.com 和 img.a.com

在www.a.com下有a.html

在img.a.com下有img.json和img.html这两个文件。

img.json就是一些我们要获取的数据:


 
  1. [
  2. {
  3. "name" : "img1",
  4. "url" : "http://img.a.com/img1.jpg"
  5. },
  6. {
  7. "name" : "img2",
  8. "url" : "http://img.a.com/img2.jpg"
  9. }
  10. ]
  11.  

img.html就是我们iframe要引用的:


 
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Insert title here</title>
  6. </head>
  7. <body>
  8. <script src="./jquery.js"></script>
  9. <script type="text/javascript">
  10. document.domain = "a.com";
  11.  
  12. var p = parent.window.$;
  13. p("#sub").text("我是子页面添加的");
  14. </script>
  15. </body>
  16. </html>
  17.  

a.html就是要通过跨子域获取数据的页面:


 
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Insert title here</title>
  6. </head>
  7. <body>
  8. <!-- 通过跨域获取数据,并添加到ul中 -->
  9. <ul id="data"></ul>
  10.  
  11. <!-- 子页面通过parent.window来访问父页面 -->
  12. <div id="sub"></div>
  13.  
  14. <!-- 通过iframe引用img.a.com下的img.html -->
  15. <iframe id="iframe" src="http://img.a.com/img.html"></iframe>
  16.  
  17. <script src="./jquery.js"></script>
  18. <script type="text/javascript">
  19. document.domain = "a.com";
  20.  
  21. $("#iframe").bind("load", function() {
  22. //获取子页面的jquery对象
  23. iframe = document.getElementById("iframe").contentWindow.$;
  24.  
  25. iframe.getJSON("http://img.a.com/img.json", function(data) {
  26. var con = "";
  27. //注意这里的$对象是www.a.com上的
  28. $.each(data, function(i, v) {
  29. con += "<li>" + v.name + ":" + v.url + "</li>";
  30. });
  31. $("#data").html(con);
  32. });
  33. });
  34. </script>
  35. </body>
  36. </html>
  37.  

a.html中我们通过contentWindow.$来获取子页面的jquery对象,然后通过getJSON获取数据,并通过www.a.com上的$对象把数据写入到ul中。

在子页面img.html中我们通过parent.window来访问父页面的$对象,并操作元素添加数据。

更多关于PHP相关内容可查看本站专题:《PHP+ajax技巧与应用小结》、《PHP网络编程技巧总结》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

希望本文所述对大家PHP程序设计有所帮助。

分享到:

相关信息

系统教程栏目

栏目热门教程

人气教程排行

站长推荐

热门系统下载