우선, IFRAME 커뮤니케이션은 동일한 도메인 커뮤니케이션 및 크로스 도메인 커뮤니케이션으로 나뉩니다.
1. 같은 도메인의 통신
소위 동일한 도메인 커뮤니케이션은 http : //localhost/demo/iframe/iframea.html에 따라 A.html 페이지의 중첩 iframe을 나타냅니다.
예 : <iframe src = "http : //localhost/demo/iframe/iframeb.html"id = "iframea"name = "iframea">이 두 페이지의 데이터가 통신합니다. 예를 들어, 부모 페이지 A.HTML의 Child 페이지의 함수를 호출하고 싶습니다. 이는 document.getElementById('iframeA').contentWindow.b(); Google에서 B는 Child Page B.html의 기능입니다. 그러나이 전화에는 내가 오랫동안 어려움을 겪고 있다는 문제가 있습니다. 즉, 다음과 같이 Firefox에서 그러한 오류를보고했기 때문에 다음과 같습니다.
B는 함수가 아니지만 하위 페이지에서 그러한 함수를 명확하게 정의 했으므로 왜 그러한 오류가 발생합니까? 신중한 분석과 Google 후에는 이해해야 할 문제가 있음을 알았습니다. Iframe이로드되지 않았을 때이 JS를 실행하고 그러한 오류를보고합니다. 그래서 Firefox에서 iframe.onload 함수를 사용하여 테스트하려고했습니다. 물론, 오류가 없었고, 맞았다. 그래서 나는 그것이이 문제라고 확신했다. 따라서 호환되는 IE 및 Firefox Google을 작성하여 Iframe이로드되었는지 확인하기 위해 기능을 작성하고 싶습니다! 실제로, 위의 메소드를 호출 할 콜백 함수를 제공하십시오.
위의 아이디어를 바탕으로 다음과 같은 코드를 쓸 수 있습니다.
<iframe src = "http : //localhost/demo/iframe/iframeb.html"id = "iframea"name = "iframea"> </iframe> <div id = "topname"> topnddddddddddddddddddddddddddddddddddddddddddddd </div> <cript> function a () {alert ( "a"); } var iframe = document.getElementById ( 'iframea'); iframeisload (iframe, function () {var obj = document.getElementById ( 'iframea'). contentWindow; obj.b ();}); 함수 iframeisload (iframe, 콜백) {if (iframe.attachevent) {iframe.attachevent ( 'onload', function () {콜백 && 콜백 ();}); } else {iframe.onload = function () {callback && callback (); }}}}} </script>B.html 코드는 다음과 같습니다.
var b = function () {alert ( "b"); } 자식 페이지의 부모 페이지의 기능을 호출하는 것은 매우 간단합니다. 이 작업을 수행하면 괜찮을 것입니다. window.parent.A();
자식 페이지는 부모 페이지 요소의 값을 취합니다 : window.parent.document.getElementById("topName").innerHTML 및 기타 메소드.
둘 : Iframe 크로스 도메인 커뮤니케이션.
IFRAME 크로스 도메인 액세스는 일반적으로 두 가지 상황으로 나뉩니다. 첫 번째는 동일한 주 영역과 다른 서브 도메인을 가진 크로스 도메인입니다. 두 번째 유형은 다음과 같습니다. 다른 메인 도메인 교차 도메인.
1. 동일한 주 영역에서 상이한 하위 도메인 사이의 교차 도메인이다. 문서를 통해 동일한 기본 도메인을 설정하여 해결할 수 있습니다.
도메인 ABC.example.com이 있다면 ABC.html이라는 페이지가 있고 다음과 같이 페이지에 iframe이 중첩되어 있습니다. <iframe src = "http://def.example.com/demop.html"id = "iframe2"style = "display : none; </iframe>에 액세스하고 싶습니다. Page ABC.html 우리는 보안 브라우저의 동일한 오리핀 정책의 한계로 인해 다른 도메인의 다른 프로토콜에서 다른 포트로 페이지를 작동 할 수 없으므로 교차 도메인 액세스가 해결됩니다. 상위 페이지 ABC.html에 JS 함수가있는 경우 : function test(){console.log(1);}; parent.test(); 이러한 방식으로 Firefox 아래의 Cross-Domain을 보면 솔루션은 각 JS 기능의 맨 위에 문장 document.domain = 'example.com' 추가하는 것입니다.
ABC.html 코드는 다음과 같습니다.
<iframe src = "http://def.example.com/demo/def.html"id = "iframe2"style = "display : none;"> </iframe> // 도메인 하위 페이지에서 상위 페이지를 호출하는 함수 (아래의 검정 기능이라고 가정) 문서 = 'example.com';
def.html 코드는 다음과 같습니다.
/** 자식 페이지의 메소드는 부모 페이지*/document.domain = 'example.com'; // window.top.test (); Window.parent.test ();
또는이 두 페이지, 부모 페이지가 다음과 같이 자식 페이지를 호출하기를 원합니다.
A.html 코드는 다음과 같습니다.
/** 도메인 부모 페이지*/document.domain = 'example.com'; var iframe = document.getElementById ( 'iframe2'); iframeisload (iframe, function () {var abj = iframe.contentWindow; obj.child ();}); if (iframe.attachevent) {iframe.attachevent ( 'onload', function () {callback && callback ();}); } else {iframe.onload = function () {callback && callback (); }}}}def.html 페이지에 자식 함수 코드가있는 경우 지금 :
document.domain = 'example.com'; function child () {console.log ( 'i am a child page');}부모 페이지를 호출하는 어린이 페이지 또는 자식 페이지에 전화하는 부모 페이지에 관계없이 도메인을 가로 질러 호출 할 수 있습니다. 모든 것이 괜찮습니다!
2. 그것은 다른 주 영역과 교차 도메인이다.
Google에는 location.hash Method, window.name Method, HTML5 및 Flash 등을 포함하여 다양한 주요 영역에서 도메인 크로스 도메인 문제에 대한 몇 가지 방법이 있지만 다음 IFRAME 메소드는 학습 할 가치가 있다고 생각합니다.
아래 그림과 같이 : Domain A.com의 Page Request.html (예 : http://a.com/demo/ajax/ajaxproxy/request.html)은 도메인 b.com (http://b.com/b.com/demo/ajaxproxy/rosproxy/rosproxy/rosproxy/rspll)에 iframe Pointing Pointing이 있습니다. 도메인 A.com은 도메인 A.com의 proxy.html로 중첩됩니다.
아이디어 : 도메인 B.com에서 a.com 도메인 요청 프로세스 .php에서 request.html 페이지를 구현하려면 요청 매개 변수를 URL을 통해 response.html로 전달하고 response.html에서 process.php로 실제 ajax 요청을 시작할 수 있습니다 (response.html 및 process.php는 도메인 b.com에 속합니다). 마지막으로, proxy.html 및 request.html은 동일한 도메인에 있으므로 Window.top을 사용하여 request.html에서 결과를 반환하여 실제 크로스 도메인을 완료 할 수 있습니다.
좋아, 먼저 페이지 구조를 살펴 보자.
A.com 도메인 아래에 다음과 같습니다.
request.html
proxy.html
B.com 도메인 아래에는 다음이 있습니다.
응답 .html
process.php
다음과 같이 request.html 페이지를 살펴 보겠습니다.
<! doctype html> <html> <head> <head> <title> 새로운 문서 </title> </head> <pid = "result"> 응답 결과가 여기에 채워집니다 </p> <aid = "endbtn"href = "javaScript : void (0)"> 크로스 도메인 요청을 클릭하여 클릭하십시오. "style ="display : none "> </iframe> <cript> document.getElementById ( 'sendbtn'). onclick = function () {var url = 'http://b.com/demo/ajax/ajaxproxy/repponse.html', fn = 'getperson', // 님이 정의 된 방법입니다. 24} ', // 요청 된 매개 변수 콜백 = "콜백"입니다. // 이것은 전체 요청 프로세스가 완료된 후 실행 된 콜백 함수입니다. 마지막 조치 CrossRequest (URL, FN, ReqData, Callback)를 실행합니다. // request} function} crossRequest (url, fn, reqdata, callback) {var server = document.getElementById ( 'serverif'); server.src = url + '? fn =' + encodeUricomponent (fn) + "& data =" + encodeUricomponent (reqdata) + "& callback =" + encodeUricomponent (콜백); } // 콜백 함수 함수 콜백 (data) {var str = "내 이름은" + data.name + "입니다. 나는" + data.sex + "입니다. 나는" + data.age + "년입니다."; document.getElementById ( "결과"). innerHtml = str; } </script> </body> </html> 이 페이지는 실제로 response.html에 관한 것입니다. GetPerson 정의한 메소드를 실행하고 매개 변수 '{ "id": 24}'를 사용하기를 원합니다. response.html은 메소드 이름 CallBack 다음 Brother Proxy.html에 전달하는 데 순전히 책임이 있습니다. proxy.html 및 request.html이 동일한 도메인에 있기 때문에 method name CallBack 얻은 후에 proxy.html을 실행할 수 있습니다.
응답 .html 코드는 다음과 같습니다.
<! doctype html> <html> <head> <head> <title> 새 문서 </title> </head> <body> <iframe id = "proxy"> </iframe> <cript> // 일반 메소드 ajax 요청 함수 _request (reqdata, url, 콜백) {var xmlhttp; if (wind } else {xmlhttp = new ActiveXobject ( "microsoft.xmlhttp"); } xmlhttp.onreadystatechange = function () {if (xmlhttp.readystate == 4 && xmlhttp.status == 200) {var data = xmlhttp.responsetext; 콜백 (데이터); }} xmlhttp.open ( 'post', url); xmlhttp.setrequestheader ( "content-type", "application/json; charset = utf-8"); xmlhttp.send (reqdata); } // URL 매개 변수를 얻는 일반 메소드 함수 _getQuery (key) {var query = location.split ( '?') 반환 값; } // ajax 요청을 process.php function getperson (reqdata, callback) {var url = 'http://b.com/demo/ajax/ajaxproxy/process.php'; var fn = function (data) {var proxy = document.getElementById ( 'proxy'); proxy.src = "http://a.com/demo/ajax/ajaxproxy/proxy.html?data=" + encodeUricomponent (data) + "& callback =" + EncodeUricomponent (Callback); }; _request (reqdata, url, fn); } (function () {var fn = _getQuery ( 'fn'), reqdata = _getQuery ( "data"), Callback = _getQuery ( "콜백"); 평가 ( ' + reqdata + "', '" + Callback + "');); </script> </body> </html>이는 실제로 request.html에서 요청을 수신하고 요청 매개 변수 및 메소드를 가져온 다음 서버 프로세스에 실제 ajax 요청을 발행 한 다음 서버에서 반환 된 데이터와 reques.html에서 proxy.html로 전달되는 콜백 함수 이름을 전달하는 것입니다.
다음으로 PHP 코드를 다음과 같이 살펴 보겠습니다 . 실제로 JSON 데이터를 반환하는 것입니다.
<? php $ data = json_decode (file_get_contents ( "php : // input")); 헤더 ( "내용 유형 : 응용 프로그램/json; charset = utf-8"); echo ( '{ "id":'. $ data-> id. ', "age": 24, "sex": "boy", "name": "huangxueming"}');?>마지막으로 proxy.html 코드가 있습니다.
<! doctype html> <html> <head> <head> <title> 새 문서 </title> </head> <body> <cript> 함수 _getUrl (키) {// 일반 메소드, URL 매개 변수 가져 오기 var query = location.href.split ( "?") "=") [1] .split ( "&") [0]); 반환 값; } (function () {var Callback = _getUrl ( "Callback"), data = _getUrl ( "data"); Eval ( "wind </script> </body> </html>이것은 또한 마지막 단계입니다. Proxy는 마지막으로 response.html을 통해 request.html을 통해 request.html에서 콜백 함수 이름을 전송하고 response.html에서 직접 전송하고 Window.top을 사용하여 request.html에 정의 된 콜백 함수를 실행했습니다.
3. Iframes의 높은 적응성 문제.
iframe 높이 적응은 두 가지 유형으로 나뉩니다. 하나는 동일한 도메인의 적응이고 다른 하나는 크로스 도메인의 적응입니다 . 동일한 영역에서 높은 적응 문제를 살펴 보겠습니다.
1. 동일한 도메인에서 고도로 적응할 수있는 iframes의 문제 :
아이디어 : 중첩 된 iframe 요소를 가져 와서 JavaScript를 통해 중첩 페이지의 최종 높이를 가져온 다음 메인 페이지에 설정하여 달성하십시오.
데모에 iframe1.html 및 iframe2.html 인 경우
다음은 다음 코드입니다.
<! doctype html> <html> <head> <title> 새로운 문서 </title> <style> *{마진 : 0; 패딩 : 0;} </style> </head> <body> <iframe src = "http://a.com/demo/ajax/iframeheight/iframe2.html"frambor = "0. id = "iframe"> </iframe> <cript> wind if (iframeid &&! winde } else if (iframeid.document && iframeid.document.body.scrollheight) {iframeid.height = iframeid.document.body.scrollheight; }}} </script> </body> </html>iframe2.html
<! doctype html> <html> <head> <head> <title> 새로운 문서 </title> <style> *{마진 : 0; 패딩 : 0;} </style> </head> <hod> <div style = "높이 : 500px;"> </div> </body> </html>iframe1 페이지의 높이를 iframe2 높이로 동적으로 설정할 수 있습니다.
2. Iframes는 도메인에 걸쳐 적응력이 높습니다.
우선, 우리는 위의 JS 메소드를 사용하여 iframes의 크로스 도메인을 제어 할 수 없다는 것을 알고 있으므로 A.com 도메인의 iframe1.html 페이지의 b.com 도메인 아래에있는 iframe2.html 페이지에 중간 키를 사용하여 iframe3.html 페이지에 iframe3.html 페이지에 iframe.html 페이지를 둥지로 만듭니다. 이러한 방식으로 iframe1.html 및 iframe3.html 페이지 iframe2.html nests iframe3.html이므로 iframe2.html이 iframe3.html의 href 값을 다시 쓸 수 있기 때문에 장벽없이 통신 할 수 있습니다.
iframe1의 내용 :
iframe1.html 컨텐츠는 주로 iframe3.html 페이지에서 전송 된 컨텐츠를 허용하고 해당 작업을 완료합니다. iframe1.html 코드는 다음과 같습니다.
<iframe src = "http://b.com/demo/ajax/iframeheight/iframe2.html"id = "iframe"> </iframe> <cript> var ifr_el = document.getElementById ( "iframe"); 함수 getifrdata (data) {ifr_el.style.height = data+"px"; } </스크립트>iframe2.html의 내용 :
iframe2.html 컨텐츠는 값을 iframe3.html 페이지로 어떻게 전달합니까? 방금 값이 iframe3.html 페이지의 href로 전달되었다고 말했으므로 iframe의 SRC를 수정하십시오. C 페이지를 새로 고칠 필요가 없으므로 해시에 의해 iframe3.html 페이지로 전달할 수 있습니다. iframe2.html의 코드는 다음과 같습니다.
<! doctype html> <html> <head> <head> <title> 새로운 문서 </title> <style> *{마진 : 0; 패딩 : 0;} </style> </head> <body> <iframe id = "iframe"src = "http://a.com/demo/ajax/iframe/iframe.html"> <cript> var oldheight = 0, ifr_el = document.getElementById ( "iframe"); t && clearinterval (t); var t = setInterVal (function () {var height = docum </script> </body> </html>기본적으로 iframe1.html 페이지의 높이는 iframe2.html을 제공하는 것이 200 픽셀이지만 iframe2.html에서는 iframe3.html에서 iframe3.html의 높이는 230 픽셀이므로 정상적인 상황에서 스크롤 막대가 있습니다. 이제 iframe2.html에서 스크롤 막대의 높이를 얻고 iframe3.html을 통해 SRC로 높이를 전달하고 iframe3.html 페이지에서 높이 값을 얻으려면 iframe1.html로 전달합니다 (iframe1.html 및 iframe3.html이 같은 도메인이기 때문에). 높이 자체는 괜찮습니다.
iframe3.html 페이지의 유일한 기능은 href를 통해 iframe2.html 페이지에서 전달한 값을 수신하고 iframe1.html 페이지로 전달하는 것입니다. iframe2.html 페이지로 전달 된 값은 타이머를 통해 지속적으로 확인하여 Location.href가 변경되었는지 확인할 수 있지만 이는 매우 비효율적입니다. 또 다른 방법은 새로운 브라우저에서 onhashchange 이벤트 (IE8+, Chrome5.0+, Firefox3.6+, Safari5.0+, Opera10.6+)를 통해 HREF의 변화를 듣는 것입니다.
iframe3.html 코드는 다음과 같습니다.
<cript> var oldheight = 0; t && clearinterval (t); var t = setInterVal (function () {var height = location.href.split ( '#') [1]; if (height && height! = oldheight) {oldheight = height; if (window.parent.parent.getifrdata) {wind </스크립트>이것은 크로스 도메인을 통해 Iframe 적응성의 높이를 달성하는 문제를 해결할 수 있습니다.
4. 요약
위는이 기사의 전체 내용입니다. 모든 사람의 연구와 일에 도움이되기를 바랍니다. 궁금한 점이 있으면 메시지를 남겨 두십시오.