201507152326_: 4 ways to implement JavaScript across domains--Introduction to JSONP and HTML5 methods

Source: Internet
Author: User

I. Jsonp method

1. Principle

In JS, it is not possible for us to request data from different domains directly with XMLHttpRequest. However, it is possible to introduce JS script files from different domains on the page.

2. Format

<script>

function DoSomething (jsondata) {

Todo

};

</script>

<script>http://example.com/data.php?callback=doSomething</script>

Two. use the newly introduced Window.postmessage method in HTML5 to transfer data across domains

1. Get the Window object. For example: var winobj = element. Contentwindow;

2. Format

A.html

<script>

function onload () {

var iframe = document.getElementById (' iframe ');

var winobj = iframe. Contentwindow;

WinObj. PostMessage (' Haha, I am a message from page a ', ' * ');

}

</script>

<iframe>id = "iframe" src = "http://www.test.com/b.html" onload= "onload ()" </iframe>

B.html

<script>

Window.onmessage = function (e) {

E = e | | Event

Alert (E.data); The PostMessage () method is stored in data.

}

</script>

201507152326_: 4 ways to implement JavaScript across domains--Introduction to JSONP and HTML5 methods

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.