Home > Web Front-end > H5 Tutorial > How to use postMessage to implement Ajax cross-domain requests in HTML5_html5 tutorial skills

How to use postMessage to implement Ajax cross-domain requests in HTML5_html5 tutorial skills

WBOY
Release: 2016-05-16 15:51:55
Original
1577 people have browsed it

Due to the restrictions of the same-origin policy, Javascript has cross-domain communication problems. Typical cross-domain problems include communication between iframe and parent, etc.

Several common solutions:

(1) document.domain iframe;
(2) Dynamically create script;
(3) iframe location.hash;
(4) flash.

I won’t go into details about these methods here. What is recorded is HTML5’s window.postMessage.
postMessage is compatible with IE8, Firefox, Opera, Safari, and Chrome.

Two foreign servers are required for testing. Of course, local and online servers can also be used as two foreign servers.
If you use phonegap to develop, you can install the request file on the client, and then dynamically request the server's data processing to obtain and display the data. In this way, any web development language and method can be used to develop the backend required by phonegap App.

1. Usage of postMessage

postMessage is a new API introduced by HTML5 to solve js cross-domain problems, allowing multiple iframes/ window cross-domain communication.

Assume the structure is as follows:

JavaScript CodeCopy content to clipboard
  1. test.html
    "wrapper">
  2. postMessage (cross-domain)

  3.  
  4.   

  5.    
  6. "text" name="message" value="son" id="message"/> 
  7. "submit"/> 
  8.  
  9.  
  10. Information from the target iframe:

  11. "test">No information yet

     

iframe.html

JavaScript CodeCopy content to clipboard
  1. iframe points to xiebiji.com

  2. "text" name="message" value="dad" id="message"/> 
  3. "submit"/>

  4. "test">No information yet.

    The following is the Javascript code (sending data) in test.html:
    var win = document.getElementById("iframe" ).contentWindow;document.querySelector('form').onsubmit=function(e){
  5. win.postMessage(document.getElementById("message").value,"*");
  6. if (e.preventDefault)
  7. e.preventDefault();
  8. e.returnValue = false;

The key code is just one sentence:

JavaScript CodeCopy content to clipboard
  1. win.postMessage(document.getElementById("message").value,"*");

PostMessage is a method of the communication object, so to communicate with the iframe, the iframe object calls the postMessage method. postMessage has two parameters, one of which is indispensable. The first parameter is the data to be passed, and the second parameter is the domain that allows communication. "*" means that the accessed domain is not judged, which can be understood as allowing communication in all domains.

Then there is the code in iframe.html that listens to receive data:

JavaScript CodeCopy content to clipboard
  1. var parentwin = window.parent;window.onmessage=function(e){ 
  2. document.getElementById("test").innerHTML = e.origin "say:" e. data;
  3. parentwin.postMessage('HI! You sent me "' e.data '". ',"*");};

It’s very simple, I believe you will understand it at a glance. e.data contains the transmitted data, and e.origin refers to the source domain.

Then iframe.html also sends response data to test.html, and test.html receives the data. If the code is similar, I won’t post the code.

2. Ajax cross-domain request

Based on the above cross-domain communication, just put the Ajax code in the onmessage processing function in iframe.html, Send the request to test.html using the data passed by postMessage as a parameter, and then pass the returned data to test.html using postMessage. In this way, cross-domain Ajax requests are implemented. It's actually a very simple thing.

Post a sample code, but it has nothing to do with the above code.

JavaScript CodeCopy content to clipboard
  1. (function(){ //Get cross-domain data window.onmessage = function(e){
  2. var url = "http://yangzebo.com/demo/noforget/test.php?msg=" e.data;
  3. //Ajax var xhr = getXHR();
  4. if(xhr){
  5. xhr.open("GET",url,true);
  6. xhr.onreadystatechange = changeHandle;
  7. xhr.send(null); }else{
  8. alert("Ajax not supported"); }
  9. function changeHandle(){//Return processing
  10. if(xhr.readyState == 4){
  11. var parentwin = window.parent;
  12. parentwin.postMessage(xhr.responseText,"*");//Sending data across domains
  13. } }
  14. function getXHR(){//Get XMLHttpRequest
  15. var xhr_temp; if(window.XMLHttpRequest){
  16. xhr_temp = new XMLHttpRequest();
  17. }else if(window.ActiveXObject){
  18. xhr_temp = new ActiveXObject("Microsoft.XMLHTTP");
  19. }else{
  20. xhr_temp = null;
  21. return xhr_temp;
  22. } };})();

Then give an unsightly demo.

If you are interested in the code request, please use the developer tools to check it out. "zebo man" is read from the database, and "my msg" is the parameter of the Ajax request sent by sendAndReceive.html to test.php. , passed back to sendAndReceive.html through test.php and iframeforAjax.html.

3. Tips

You need to get the contentWindow of the iframe to call postMessage.

postMessage must be called after the iframe is loaded to run normally. (This took me a long time)

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template