利用iframe實現ajax 跨域通信的解決方案


  在漫長的前端開發旅途上,無可避免的會接觸到ajax,而且一般情況下都是用在同一域下的ajax請求;但是如果請求是發生在不同的域下,請求就無法執行,並且會拋出異常提示不允許跨域請求,目前我沒有找到明確的資料說明這是為什么,我覺得應該是出於安全性的考慮吧。縱然如此,要實現跨域訪問的話,方法還是有的,而且不只一種,在這里介紹其中一種解決方案:如何利用iframe完成ajax的跨域請求。

  

 

 

  如下圖所示:域a.com的頁面request.html(即http://a.com/request.html)里面嵌套了一個iframe指向域b.com的response.html,而response.html里又嵌套了域a.com的proxy.html。

  要實現域a.com的request.html請求域b.com的process.php,可以將請求的參數通過URL傳給response.html,由response.html向process.php發出真正的ajax請求(response.html與process.php都屬於域b.com),然后將返回的結果通過URL傳給proxy.html,最后由於proxy.html與request.html是在同一域下,所以可以在proxy.html利用window.top將結果返回給request.html完成跨域通信。

  整個流程的思路其實非常清晰,真正的ajax請求並不是發生在域a.com,而是發生在域b.com;而域a.com是做了兩件事,第一件事是由request.html完成,向域b.com發送傳入參數;第二件事由proxy.html完成,把域b.com的響應數據遞回給request.html。

跨域訪問流程圖

  OK,接下來就是如何用代碼實現了;在此之前先看文檔結構:

  http://a.com/

    request.html

    proxy.html

  http://b.com/

    response.html

    process.php

 

1、先來看request.html,為了方便理解,我把js也放到了頁面上:

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 5     <title>該頁面的路徑是:http://a.com/request.html</title>
 6 </head>
 7 <body>
 8     <p id="result">這里將會填上響應的結果</p>
 9     <a id="sendBtn" href="javascript:void(0)">點擊,發送跨域請求</a>
10     <iframe id="serverIf"></iframe>
11     <script type="text/javascript">
12         document.getElementById("sendBtn").onclick = function() {
13             var url = "http://b.com/response.html";
14             var fn = "GetPerson";//這是定義在response.html的方法 15             var reqdata = '{"id" : 24}';//這是請求的參數 16             var callback = "CallBack";//這是請求全過程完成后執行的回調函數,執行最后的動作 17             CrossRequest(url, fn, reqdata, callback);//發送請求 18         }
19         function CrossRequest(url, fn, reqdata, callback) {
20             var server = document.getElementById("serverIf");
21             server.src = url + "?fn=" + encodeURIComponent(fn) + "&data=" + encodeURIComponent(reqdata) + "&callback=" + encodeURIComponent(callback);//這里由request.html向response.html發送的請求其實就是通過iframe的src將參數與回調方法傳給response.html 22         }
23         function CallBack(data) {//回調函數 24             var str = "My name is " + data.name + ". I am a " + data.sex + ". I am " + data.age + " years old.";
25             document.getElementById("result").innerHTML = str;
26         }
27     </script>
28 </body>
29 </html>

  看代碼和注釋相信都很容易理解,這個頁面其實就是要告訴response.html:我要讓你執行你定義好的方法GetPerson,並且要用我給你的參數'{"id" : 24}'。可能感到模糊的就是為什么要把CallBack函數傳給response.html,這是定義在本頁面上的方法,response.html也不能執行它;看接下來的代碼就會知道:response.html純粹是負責將CallBack這個方法名傳遞給下一位仁兄proxy.html,而proxy.html拿到了CallBack這個方法名就可以執行了,因為proxy.html和request.html是同域的。

 

2、接下來我們看response.html的代碼:

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 5 <title>該頁面的路徑是:http://b.com/response.html</title>
 6 </head>
 7 <body>
 8     <iframe id="proxy"></iframe>
 9     <script type="text/javascript">
10         function _request(reqdata, url, callback) {//通用方法,ajax請求 11             var xmlhttp;
12             if (window.XMLHttpRequest) {
13                 xmlhttp = new XMLHttpRequest();
14             }
15             else {
16                 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
17             }
18             xmlhttp.onreadystatechange = function () {
19                 if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
20                     var data = xmlhttp.responseText;
21                     callback(data);
22                 }
23             }
24             xmlhttp.open("POST", url);
25             xmlhttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");
26             xmlhttp.send(reqdata);
27         }
28         function _getQuery(key) {//通用方法,獲取url參數 29             var query = location.href.split("?")[1];
30             var value = decodeURIComponent(query.split(key + "=")[1].split("&")[0]);
31             return value;
32         }
33         function GetPerson(reqdata, callback) {//向process.php發送ajax請求 34             var url = "process.php";
35             var fn = function(data) {
36                 var proxy = document.getElementById("proxy");
37                 proxy.src = "http://b.com/Proxy.html?data=" + encodeURIComponent(data) + "&callback=" + encodeURIComponent(callback);
38             }
39             _request(reqdata, url, fn);
40         }
41         (function() {
42             var fn = _getQuery("fn");
43             var reqdata = _getQuery("data");
44             var callback = _getQuery("callback");
45             eval(fn + "('" + reqdata +"', '" + callback + "')");
46         })();
47     </script>
48 </body>
49 </html>

   這里其實就是接收來自request.html的請求得到請求參數和方法后向服務器process.php發出真正的ajax請求,然后將從服務器返回的數據以及從request.html傳過來的回調函數名傳遞給proxy.html。

 

3、接下來看一下process.php的代碼,比較簡單:

1 <?php 
2 $data = json_decode(file_get_contents("php://input"));
3 header("Content-Type: application/json; charset=utf-8");
4 echo ('{"id" : ' . $data->id . ', "age" : 24, "sex" : "boy", "name" : "huangxueming"}');
5 ?>

這幾句代碼就不打算講了,稍微有點PHP基礎都能看懂,沒PHP基礎的應該都能看出個大概了,呵呵~~~

 

4、最后就是proxy.html了:

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 5     <title>該頁面的路徑是:http://a.com/proxy.html</title>
 6 </head>
 7 <body>
 8     <script type="text/javascript">
 9         function _getUrl(key) {//通用方法,獲取URL參數 10             var query = location.href.split("?")[1];
11             var value = decodeURIComponent(query.split(key + "=")[1].split("&")[0]);
12             return value;
13         }
14         (function() {
15             var callback = _getUrl("callback");
16             var data = _getUrl("data");
17             eval("window.top." + decodeURIComponent(callback) + "(" + decodeURIComponent(data) + ")");
18         })()
19     </script>
20 </body>
21 </html>

  這里也是最后一步了,proxy終於拿到了request.html透過response.html傳過來的回調函數名以及從response.html直接傳過來的響應數據,利用window.top執行request.html里定義的回調函數。

  實際應用中,proxy.html基本上可以是一個通用的代理,無需改動,如果需要用到很多跨域方法,這些方法都可以在域a.com里面加上,而域b.com就相當於定義一些接口供a.com調用,如GetPerson,當然這並不是真正的接口,只是方便理解,打個比方;另外,當然就是要把iframe隱藏起來。OK,最后還是奉上那句老話:所擁有的技術並不是最重要的,最重要的是學習的能力。

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM