1. 程式人生 > 程式設計 >PHP ajax跨子域的解決方案之document.domain+iframe例項分析

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程式設計有所幫助。