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

吾爱主题 阅读:155 2021-10-06 13:28:00 评论:0

本文实例讲述了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 4 5 6 7 8 9 10 [    {      "name" : "img1" ,      "url" : "http://img.a.com/img1.jpg"    },    {      "name" : "img2" ,      "url" : "http://img.a.com/img2.jpg"    } ]

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

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

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

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

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

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

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

原文链接:https://www.cnblogs.com/jkko123/p/6294623.html

可以去百度分享获取分享代码输入这里。
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

【腾讯云】云服务器产品特惠热卖中
搜索
标签列表
    关注我们

    了解等多精彩内容