• 企业400电话
  • 微网小程序
  • AI电话机器人
  • 电商代运营
  • 全 部 栏 目

    企业400电话 网络优化推广 AI电话机器人 呼叫中心 网站建设 商标✡知产 微网小程序 电商运营 彩铃•短信 增值拓展业务
    PHP ajax跨子域的解决方案之document.domain+iframe实例分析

    本文实例讲述了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就是一些我们要获取的数据:

    [
      {
        "name" : "img1",
        "url" : "http://img.a.com/img1.jpg"
      },
      {
        "name" : "img2",
        "url" : "http://img.a.com/img2.jpg"
      }
    ]
    
    

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

    !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就是要通过跨子域获取数据的页面:

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

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

    您可能感兴趣的文章:
    • PHP下ajax跨域的解决方案之window.name实例分析
    • PHP下ajax跨域的解决方案之jsonp实例分析
    • PHP处理Ajax请求与Ajax跨域问题
    • jquery ajax结合thinkphp的getjson实现跨域的方法
    • PHP中运用jQuery的Ajax跨域调用实现代码
    • php+mysql+ajax 局部刷新点赞/取消点赞功能(每个账号只点赞一次)
    • Jquery+AJAX实现无刷新上传并重命名文件操作示例【PHP后台接收】
    • PHP使用ajax的post方式下载excel文件简单示例
    • PHP Ajax跨域问题解决方案代码实例
    上一篇:PHP下ajax跨域的解决方案之jsonp实例分析
    下一篇:PHP下ajax跨域的解决方案之window.name实例分析
  • 相关文章
  • 

    © 2016-2020 巨人网络通讯

    时间:9:00-21:00 (节假日不休)

    地址:江苏信息产业基地11号楼四层

    《增值电信业务经营许可证》 苏B2-20120278

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