Implementation principle of ajax cross-origin communication using iframe (illustration)

Source: Internet
Author: User

In the long journey of front-end development, ajax is inevitable and generally used for ajax requests in the same domain. However, if a request occurs in different domains, the request cannot be executed, and an exception will be thrown, prompting that the cross-origin request is not allowed. Currently, I have not found any clear information about the reason. I think it should be for security considerations. In this case, there are still some methods to implement cross-origin access. Here we will introduce one solution: How to Use iframe to complete ajax cross-origin requests.

As shown in: domain a.compage request.html (that is, http://a.com/request.html embedded in a iframedirected domain B .comresponse.html, and response.html embedded in the domain a.comproxy.html.

Complete the cross-origin communication.

.

Cross-origin access Flowchart

OK. The next step is how to use the code. Before that, let's take a look at the document structure:

Http://a.com/

Request.html

Proxy.html

Http:// B .com/

Response.html

Process. php

1 second, let's first look at request.html. For ease of understanding, I also put js on the page:
Copy codeThe Code is as follows:
<! DOCTYPE html>
<Html>
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8">
<Title> the path to this page is: http://a.com/request.html </title>
</Head>
<Body>
<P id = "result"> the response result is entered here </p>
<A id = "sendBtn" href = "javascript: void (0)"> click to send a cross-origin 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 response.html method.
Var reqdata = '{"id": 24}'; // This is the request parameter.
Var callback = "CallBack"; // This is the callback function executed after the entire request process is completed, and the final action is executed.
CrossRequest (url, fn, reqdata, callback); // send a request
}
Function CrossRequest (url, fn, reqdata, callback ){
Var server = document. getElementById ("serverIf ");
Server. src = url + "? Fn = "+ encodeURIComponent (fn) +" & data = "+ encodeURIComponent (reqdata) +" & callback = "+ encodeURIComponent (callback); // callback
}
Function CallBack (data) {// CallBack function
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>
</Html>

The code and comments are easy to understand. This page is actually called response.html: I want you to execute the GetPerson method you have defined and use the parameter '{"id": 24}' that I have given you }'. It can be seen that the callback should be passed to response.html, which is defined on the page, and response.html cannot execute it. The following code will know that the callback is in the same domain.

2 seconds to see the response.html code:
Copy codeThe Code is as follows:
<! DOCTYPE html>
<Html>
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8">
<Title> the path to this page is: http:// B .com/response.html </title>
</Head>
<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 to obtain url parameters
Var query = location. href. split ("? ") [1];
Var value = decodeURIComponent (query. split (key + "=") [1]. split ("&") [0]);
Return value;
}
Function GetPerson (reqdata, callback) {// send an 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>
</Html>

.

3. Next, let's take a look at the process. php code, which is relatively simple:
Copy codeThe Code is as follows:
<? Php
$ Data = json_decode (file_get_contents ("php: // input "));
Header ("Content-Type: application/json; charset = UTF-8 ");
Echo ('{"id ":'. $ data-> id. ', "age": 24, "sex": "boy", "name": "huangxueming "}');
?>

I'm not going to talk about these code statements. I can understand the basics of PHP a little bit, but I should be able to see it if I don't have the basics of PHP ~~~

4、the last step is proxy.html:
Copy codeThe Code is as follows:
<! DOCTYPE html>
<Html>
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8">
<Title> the path to this page is: http://a.com/proxy.html </title>
</Head>
<Body>
<Script type = "text/javascript">
Function _ getUrl (key) {// common method to obtain URL parameters
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>
</Html>

Callback function defined in callback.

In the example application, proxy.html can basically be a common proxy without modification. If you need to use many cross-origin methods, these methods can be added in the domain a.com, domain B .com is equivalent to defining some interfaces for a.com calls, such as GetPerson. Of course, this is not a real interface, but it is easy to understand. For example, of course, you must hide the iframe. OK. The last sentence is the old saying: the technology is not the most important, but 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.