Using PostMessage knowledge points in HTML5 to resolve post cross-domain problems in Ajax _ajax related

Source: Internet
Author: User
Tags php code

Because of the restriction of homology policy, JavaScript has the problem of cross-domain communication, and the typical cross-domain problem is the communication between IFRAME and parent. A few common solutions:

(1) Document.domain+iframe (2) dynamically creating script, (3) Iframe+location.hash; (4) Flash.

PostMessage is a new API introduced by HTML5 to address JS cross-domain problems, allowing multiple Iframe/window to communicate across domains.

HTML5 provides the ability to receive and send information to and from each other in a Web page document. With this feature, as long as you get to an instance of the Window object where the page is located, you can communicate with each other not only with the same source (domain + port number), but even across domains.

Browser support degree: ie8+,firefox4+,chrome8+ opera10+

1. First of all, to receive messages from other windows, you must listen to the message event for the Window object, as follows:

Copy Code code as follows:

Window.addeventlistener ("Message", function () {},false);

2. Second, you need to send a message to another window using the PostMessage method of the Window object, which is defined as follows:

Copy Code code as follows:

Otherwindow.postmessage (message, targetorigin);

The method uses 2 parameters, the first parameter is the message text that is sent, but it can also be any JavaScript object, and the second parameter is the URL address of the object window that receives the message (for example: http:127.0.0.1:8080/), But we can also use the wildcard character "*" in the URL address string to specify all the fields, but we recommend using a specific domain name, Otherwindow, to send a reference to the Window object.

Demo Demo:

If I am now under the Hosts file, bind 2 domain names as follows:

127.0.0.1 abc.example.com
127.0.0.1 longen.example.com

Now if there is a abc.html page under the abc.example.com domain, there is def.html page under the longen.example.com domain, now I hope that these 2 different domains under the page can communicate with each other, abc.html code as follows:

<form> 
   <p> 
    <label for= "message" style= "COLOR:RED;FONT-SIZE:24PX;" > Send an information to the iframe window:</label> 
    <input type= "text" name= "message" value= "send" id= "Messages"/> 
    <input type= "Submit" value= "submit" id= "Submit"/> 
   </p> 
</form> 
 
 

The JS code is as follows:

var win = document.getElementById ("iframe"). Contentwindow;
document.getElementById ("Submit"). onclick = function (e) {
  e.preventdefault ();
  Win.postmessage (document.getElementById ("message"). Value, "http://longen.example.com"); 
Window.addeventlistener ("Message", function (e) {
   e.preventdefault ();
   document.getElementById ("Test"). InnerHTML = "The message passed from + e.origin +": \ n "+ e.data;
},false);

The def.html code is as follows:

HTML code:

<form> 
   <p> 
    <label for= "message" > Send abc.html to the parent window:</label> 
    <input type= "Text" name= "message" value= "send" id= "message"/> 
    <input type= "Submit"/> 
   </p> 
 </ form> 
 <p id= "Test2" > Temporarily no information. </p>

The JS code is as follows:

var parentwin = window.parent; 
Window.addeventlistener ("Message", function (e) {
    document.getElementById ("Test2"). InnerHTML = "field from parent window" + E.origin + ", and content data:" + e.data; 
    Parentwin.postmessage (' hi! you sent me a ' <span> ' +e.data+ ') </span>. ', "http://abc.example.com");
},false);

When I click on the abc.html page, I can see the effect as follows and return the content from def.html. As follows:

We need to know the following message:

You can receive messages by listening to the message events for the Window object.
By accessing the Origin property of the message event, you can get the sending source of messages.
The message content can be obtained by accessing the data property of the messages event.
Send a message using the PostMessage method.
By accessing the Source property of the message event, you can get the window object for the source of the messages (which, exactly, should be the proxy object for the window).
With the basics above, we can extend the problem of implementing Ajax post Cross-domain.

Two: Using PostMessage knowledge points to solve the post Cross-domain problem in Ajax.

Principle: The principle is also very simple, if our domain name abc.example.com under the abc.html page needs to send the AJAX request (Cross-domain, domain name is longen.example.com), then we still first cross the page document the form, and above, We can now create a page under the longen.example.com, such as called def.html. So we're still embedding a hidden field in the Abc.html page. The iframe src path points to the def,html page under the longen.example.com domain. The procedure is similar to a cross document, but now write an AJAX request within the Window.onmessage event in the Def.html page, as follows:

The abc.html page under Abc.example.com is as follows:

The HTML code is the same as above, and the following is the JS code:

var win = document.getElementById ("iframe"). Contentwindow;
document.getElementById ("Submit"). onclick = function (e) {
   e.preventdefault ();
   Win.postmessage (document.getElementById ("message"). Value, "http://longen.example.com/"); 
Window.addeventlistener ("Message", function (e) {
  e.preventdefault ();
  Alert (typeof E.data)
  var json = Json.parse (e.data);
   Console.log (JSON);
  Alert (Json.url)
},false);

The def.html code is as follows:

The JS code is as follows:

Get cross-domain data 
window.onmessage = function (e) { 
   $.ajax ({
     URL: ' http://longen.example.com/webSocket/test.php ' ,
     type: ' POST ',
     dataType: ' text ',
     //data: {msg:e.data},
     success:function (res) {
        var parentwin = window.parent; 
        Parentwin.postmessage (res, "http://abc.example.com");//cross-domain Send data 
     }
   };
 

The test.php code is as follows:

<?php 
  $data =array ( 
   url =>1,
   name => ' 2 ',
   ' xx-xx ' => ' xx '
 );
 echo Json_encode ($data);
? >

The Ajax post Cross-domain can be implemented as implemented on the way.

The above content is about using the HTML5 postmessage knowledge point to solve the post Cross-domain problem in Ajax related introduction, I hope you like.

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.