Realization principle of Ajax cross-domain communication using IFRAME (diagram) _ajax related

Source: Internet
Author: User
Tags eval

During the long front-end development journey, it is inevitable to be exposed to Ajax, in general, Ajax requests are used under the same domain, but if the request is in a different domain, the request cannot be executed, and an exception is thrown to not allow cross-domain requests, so I don't have a clear description of why that is. I think it should be for safety reasons. Even so, there is a way to achieve cross-domain access, and more than one, where you can describe one solution: how to use an IFRAME to complete Ajax Cross-domain requests.

As shown in the following figure: the page request.html of the domain a.com (that is, http://a.com/ request.html) inside nested an iframe point to the domain B.Com response.html, and response.html nested domain a.com proxy.html.

To implement the process.php of the domain a.com request.html request domain B.Com, the requested parameter can be passed to response.html by the URL, and a real Ajax request is sent to response.html by process.php (response.ht Both ML and process.php belong to the domain B.Com, and then the returned results are passed through the URL to proxy.html, and finally because Proxy.html and request.html are under the same domain, proxy.html can be used window.top to return the results to req uest.html Complete Cross-domain communication.

The whole process of thinking is actually very clear, The real Ajax request does not occur in the domain a.com, but in the domain B.Com, and the domain a.com is doing two things, the first one is done by request.html, sending the incoming parameters to the domain B.Com, and the second one is completed, and the response data of the domain proxy.html is handed back to B.Com St.html.

Cross-domain Access flowchart

OK, the next step is how to do it in code, and before that, look at the structure of the document:

http://a.com/

Request.html

Proxy.html

http://b.com/

Response.html

process.php

1, first to see request.html, in order to facilitate understanding, I put JS also put on the page:

Copy Code code as follows:

<! DOCTYPE html>
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">
<title> the path to the page is:http://a.com/request.html</title>
<body>
<p id= "Result" > here will fill in the results of the response </p>
<a id= "sendbtn" href= "javascript:void (0)" > Click to send cross domain request </a>
<iframe id= "Serverif" ></iframe>
<script type= "Text/javascript" >
document.getElementById ("Sendbtn"). onclick = function () {
var url = "Http://b.com/response.html";
var fn = "Getperson";//This is the method defined in response.html
var reqdata = ' {' id ': 24} ';//This is the requested parameter
var callback = "callback";//This is the callback function that executes after the request is complete, performing the last action
Crossrequest (URL, FN, reqdata, callback);/Send Request
}
function crossrequest (URL, FN, Reqdata, callback) {
var server = document.getElementById ("Serverif");
SERVER.SRC = URL + "? fn=" + encodeURIComponent (FN) + "&data=" + encodeuricomponent (reqdata) + "&callback=" + encod Euricomponent (callback)//The request sent by request.html to Response.html is actually passing the parameter and callback method to response.html
}
function CallBack (data) {//callback functions
var str = "My name is" + Data.name +. I am a "+ Data.sex +". I am "+ data.age +" years old. "
document.getElementById ("Result"). InnerHTML = str;
}
</script>
</body>

Looking at the code and the comment is very easy to understand, this page is actually to tell response.html: I want you to perform the method you define Getperson, and to use the parameter I gave you ' {' id ': 24} '. Perhaps the blur is why the callback function is passed to response.html, a method defined on this page, and response.html cannot execute it; the next code will know: Response.html is solely responsible for passing callback this method name to the A man proxy.html, and Proxy.html got the callback this method name can be executed, because proxy.html and request.html are the same domain.

2, next we look at the response.html code:

Copy Code code as follows:

<! DOCTYPE html>
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">
<title> the path to the page is:http://b.com/response.html</title>
<body>
<iframe id= "proxy" ></iframe>
<script type= "Text/javascript" >
function _request (reqdata, URL, callback) {//Common method, Ajax request
var xmlhttp;
if (window. XMLHttpRequest) {
XMLHTTP = new XMLHttpRequest ();
}
else {
XMLHTTP = new ActiveXObject ("Microsoft.XMLHTTP");
}
Xmlhttp.onreadystatechange = function () {
if (xmlhttp.readystate = = 4 && xmlhttp.status = 200) {
var data = Xmlhttp.responsetext;
callback (data);
}
}
Xmlhttp.open ("POST", url);
Xmlhttp.setrequestheader ("Content-type", "Application/json; Charset=utf-8 ");
Xmlhttp.send (Reqdata);
}
function _getquery (key) {//Common method, get URL parameter
var query = Location.href.split ("?") [1];
var value = decodeuricomponent (query.split (key + "=") [1].split ("&") [0]);
return value;
}
function Getperson (Reqdata, callback) {//Send Ajax request to process.php
var url = "process.php";
var fn = function (data) {
var proxy = document.getElementById ("proxy");
PROXY.SRC = "Http://b.com/Proxy.html?data=" + encodeuricomponent (data) + "&callback=" + encodeuricomponent ( callback);
}
_request (reqdata, URL, fn);
}
(function () {
var fn = _getquery ("FN");
var reqdata = _getquery ("Data");
var callback = _getquery ("callback");
Eval (fn + "(' + reqdata +" ', ' "+ Callback +") ");
})();
</script>
</body>

This is actually receiving requests from request.html request parameters and methods to send a real AJAX request to the server process.php, and then pass the data returned from the server and the name of the callback function passed from the request.html to proxy.html.

3, next look at the process.php code, relatively simple:

Copy Code code as follows:

<?php
$data = Json_decode (file_get_contents ("Php://input"));
Header ("Content-type:application/json; Charset=utf-8 ");
Echo (' {' id ': '. $data->id. ', "Age": "Sex": "Boy", "name": "Huangxueming"} ");
?>

These few code is not going to say, a little bit of PHP basis can understand, no PHP based on should be able to see a probably, hehe ~ ~ ~

4, the last is proxy.html:

Copy Code code as follows:

<! DOCTYPE html>
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">
<title> the path to the page is:http://a.com/proxy.html</title>
<body>
<script type= "Text/javascript" >
function _geturl (key) {//Common method, get URL parameter
var query = Location.href.split ("?") [1];
var value = decodeuricomponent (query.split (key + "=") [1].split ("&") [0]);
return value;
}
(function () {
var callback = _geturl ("callback");
var data = _geturl ("Data");
Eval ("window.top." + decodeuricomponent (callback) + "(" + decodeuricomponent (data) +) ");
})()
</script>
</body>

This is also the last step, Proxy finally got the callback function name that request.html passed through response.html and the response data from response.html, using Window.top to execute the callback function defined in request.html.

In practical applications, Proxy.html can basically be a generic agent, without changes, if you need to use a lot of cross-domain methods, these methods can be added in the domain a.com, and the domain B.Com is equivalent to define some interface for A.com call, such as Getperson, of course, this is not a real interface, just easy to understand, for example In addition, of course, is to hide the iframe. OK, finally or the old saying: the technology is not the most important, the most important thing is the ability to learn.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.