A cross-domain method for the implementation of JS examples

Source: Internet
Author: User
Tags eval json script tag

The example of this article describes the method of JS implementation cross-domain. Share to everyone for your reference. The specific analysis is as follows:

Due to the restriction of the homology policy, XMLHttpRequest only allows resources to be requested for the current source (including domain names, protocols, ports).

The difference between JSON and JSONP:

JSON is a data interchange format, and Jsonp is an unofficial Cross-domain data interaction protocol that relies on developers to create it.

Script tags are often used to load resources under different domains and can bypass the homology policy. (You can get an exotic file with SRC attributes).

If the requested remote data itself is a section of executable JS, then these JS will be executed (equivalent to eval).

Method One:

Use the Script tag request ()

Before using the script tag request, a declaration call to the callback function is made.

?

1 2 3 4 <script> function callback function name (data) {.... } </script> <script src= "http://....jsp?callback= callback function name" ></script>

Using JSON to pass JavaScript objects is one of the easiest ways to communicate across domains called JSONP.

Remote Server Patchwork string:

callback function name ({"name1": "Data1", "name2", "Data2"})

This is a background piece of JSON data, using callback function to return to the client

(You can directly call the equivalent of a string that has been fetched for eval processing)

For example:

?

1 2 function Databack (data) {alert (DATA.NAME1)}//Will output display "Data1"

Method Two:

jquery is simpler to implement exotic loading methods (same as Ajax asynchronous requests)

?

1 2 3 4 5 $.ajax ({type: ' Get ', DataType: ' JSON ', success:function (data) {alert (data.name1)};})

or abbreviated form.

?

1 2 3 4 var url = "http://.....jsp?callback=?"; The callback value here in jquery can be arbitrary,//Because jquery is processed using the success callback function for data acceptance; $.getjson (URL, function (data) {alert ( DATA.NAME1)});

Method Three:

Ajax cross-domain service-side proxies

Set up an agent (proxy.jsp ...) in the background of the homologous;

interacts with exotic servers on the server side.

The jquery foreground transmits data:

For example:

?

1 2 3 4 5 6 7 8 9 10 $.get (' http://... jsp ',//Agent address {name1: "Data1", Name2: "Data2"}, function (data) {if (data = 1 Alert (' Send success!    '); } );

Processing of background data:

?

1 2 3 4 5 6 String data1 = Request.getparameter ("name1"); ...//Here the URL is an address under another domain with a parameter String URL = "http://.....com/.../sss.jsp?" + "name1=" + data1+ "name2=" + data2; Jumps to another field for data processing and returns the JSON-formatted data request.getrequestdispatcher (URL). Forward (Request,response);

Method Four:

Using the SRC attribute of the IFRAME tag, cross domain access is used to store the acquired value in the current IFRAME and then the same page to obtain the value within the body of the IFRAME.

?

1 2 3 4 5 6 7 8 9 10 <body> <div id= "show" ></div> <iframe id= "Frame" style= "display:none;" ></iframe> </body> <script> $ ("#frame"). attr ("src", "path time=" + New Date (). GetTime ()). Load ( function () {//Gets the value of the IFRAME label and gets it, which is displayed to the page $ ("#show"). Append ("[Data:" + $ ($ ("#frame"). Get (0). contentdocument). Find (" Body "). Text () +"] "); }); </script>

Method Five:

WebSocket can be accessed across domains in HTML5;

Create a WebSocket object:

The code is as follows:

var ws = new WebSocket (URL);

The types of events mainly handled are (ONOPEN,ONCLOSE,ONMESSAGE,ONERROR);

For example:

?

1 2 3 4 5 Ws.onopen = function () {Console.log ("open");//Send Data Ws.send ("open") to the background;}

Background can be java,php,nodejs and so on, the data processing with time OnMessage event for the return of the value of the front-end processing.

?

1 2 3 Ws.onmessage = function (Eve) {console.log (eve.data);}

I hope this article will help you with your JavaScript programming.

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.