Several common methods of cross-domain request data

Source: Internet
Author: User

Because of the influence of JS homologous policy, when requesting other domain names under a domain name, or the same domain name, URLs under different ports, it becomes an disallowed cross-domain request.

That's usually how to solve this time, the rookie bald I did a little to tidy up:

1.JavaScript

In the case of native JS (without jquery and Ajax support), usually the client code is like this (I assume it is under the port of localhost:8080 http://localhost:8080/webs/i.mediapower.mobi/ Add the following code below the body tag of the wutao/index.html page:

<script>    varnew  XMLHttpRequest ();    Xhr.open (true);     function () {        if (xhr.readystate = = 4 && xhr.status = =) {            Console.log ( Xhr.responsetext);        }    };    Xhr.send (null); </script>

Save, the browser opens http://localhost:8080/webs/i.mediapower.mobi/wutao/index.html, and the console console opens:

Browser very ruthless to you pop up a homologous limitation of the error, meaning that you cannot cross-domain request URL data.

So, I'll take the first strategy, using the script tag in HTML, insert the JS script:

(1) using the script tag reference, write the URL address of the src that you need, such as:

<script>varcallbackfunctionfunction(data) {    Console.log (' I'm a cross-domain request for data---' +  data.name);}; </script><script src= "Http://i2.mediapower.mobi/adpower/vm/Bora/js/test.js? callback=callbackfunction"></script>

Here I define a callbackfunction function, and then use the SRC attribute of the script tag to request data across domains, so the contents of Test.js are agreed and need to be written like this:

1 callbackfunction ({"Name": "Wwwwwwwwwwww"});

Save, open index.html and refresh:

(2) You can also dynamically add the script tag, let HTML parsing, dynamic loading script script, and request the remote data:

<script>varfunction(data) {    console.log (' I am a cross-domain request----' + data.name);}; var Script = document.createelement (' script '),    = document.getElementsByTagName (' body ');  = ' http://i2.mediapower.mobi/adpower/vm/Bora/js/test.js?callback=callbackfunction ';  body[0].appendchild (script); </script>

The result is the same as above.

$.ajax in 2.jQuery ()

Imagine when you want to use jquery to request cross-domain data, such as (or just index.html):

<script src= "Js/jquery-1.11.3.js" ></script><script>$ (function() {    $. Get (' http://i2.mediapower.mobi/adpower/vm/Bora/js/test.js ',function(data) {        Console.log ( (data);})    }) </script>

Browser or ruthless error, because you this URL is different from the domain name.

So since jquery encapsulates the AJAX approach, why don't we just wrap it up, and you don't have to, do you want to be guilty of it, code like this:

<script src= "Js/jquery-1.11.3.js" ></script><script>$(function() {$.ajax ({async:false, type:"GET", DataType:' Jsonp ', Jsonp:' Callback ', Jsonpcallback:' Callbackfunction ', URL:"Http://i2.mediapower.mobi/adpower/vm/Bora/js/test.js", Data:"", timeout:3000, ContentType:"Application/json;utf-8", Success:function(msg)        {Console.log (msg); }    });})
</script>

When you have done so much work, the browser is very refreshing to give a response, it is very cool, returned to you an object, which is the remote domain name under the test.js of the data.

3.postmessage+iframe

PostMessage is a new feature added in HTML5, such as I am in the local domain name, http://192.168.1.152:8080/webs/i.mediapower.mobi/wutao/testa.html in the testa.html:

<!DOCTYPE HTML><HTMLLang= "en"><Head>    <MetaCharSet= "UTF-8">    <title>Testa</title></Head><Script>window.onload= function() {document.getElementById ('IFR'). Contentwindow.postmessage (' I was going to pass the data', 'http://i2.mediapower.mobi/adpower/vm/Bora/testb.html');};</Script><Body>    <iframeID= "IFR"src= "http://i2.mediapower.mobi/adpower/vm/Bora/testb.html"></iframe></Body></HTML>

At this point, the contents of my remote testb.html should look like this:

<!DOCTYPE HTML><HTMLLang= "en"><Head>    <MetaCharSet= "UTF-8">    <title>Testb</title></Head><Script>Window.addeventlistener ('message', function(event) {//To determine the source address of a message by Origin property    if(Event.origin=== 'http://192.168.1.152:8080') {alert (event.data); }}, false);</Script><Body>123</Body></HTML>

Save the code, open the local testa.html, and access the remote testb.html

Summed up, jquery is very useful, basically JS capable things, jquery can be very fast and efficient completion, of course, the original JS can also solve a lot of things, and HTML5 's new features are very powerful, these methods, I was the most important jquery.

Several common methods of cross-domain request data

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.