Examples of cross-origin method implementation in js, and details of js instances

Source: Internet
Author: User

Examples of cross-origin method implementation in js, and details of js instances

This example describes how to implement cross-origin in JavaScript. Share it with you for your reference. The specific analysis is as follows:

Due to the same-origin policy restrictions, XMLHttpRequest only allows requests to resources of the Current Source (including domain names, protocols, and ports.

Differences between json and jsonp:

JSON is a data exchange format, while JSONP is an unofficial cross-domain data exchange protocol created by developers.

Script tags are often used to load resources in different domains and bypass the same-origin policy. (All files with the src attribute can be obtained from other countries ).
If the remote data requested is a piece of executable js, The js will be executed (equivalent to eval ).

Method 1:

Use the script tag request (<script src = "http://....jsp? Callback = callback function name "> </script>)
Before using the script tag request, declare the call of the callback function,

<Script> function callback function name (data ){.... } </Script> <script src = "http://....jsp? Callback = callback function name "> </script>

JSON is the simplest way to transmit javascript objects. This cross-domain communication method is called JSONP.

Remote Server patchwork string:

Callback Function Name ({"name1": "data1", "name2", "data2 "})

This type of json data is pieced together in the later stage and returned to the client in the form of passing parameters through the callback function.
(You can directly call eval equivalent to processing the obtained string)

For example:

Function databack (data) {alert (data. name1)} // "data1" is displayed"

Method 2:

Jquery makes it easier to implement exotic loading methods (the same as ajax asynchronous request methods)

$.ajax({  type : "get",  dataType:"json",  success : function(data){ alert(data.name1) };})

Or short form

Var url = "http://.....jsp? Callback =? "; // In jquery, the callback value can be any. // after processing, jquery uses the success callback function to accept data. $. getJSON (url, function (data) {alert (data. name1 )});

Method 3:

Ajax cross-origin server proxy

Set a proxy (proxy. jsp...) in the background of the same source ...);
Interact with exotic servers on the server side.

Jquery front-end data transmission:

For example:

$. Get ('HTTP ://.... Jsp ', // proxy address {name1: "data1", name2: "data2"}, function (data) {if (data = 1) alert (' sent successfully! ');});

Background data processing:

String data1 = request. getParameter ("name1 ");........ // The url here is the address of another domain with the parameter String url = "http://.....com/.../sss.jsp? "+" Name1 = "+ data1 +" name2 = "+ data2; // jump to another domain to process the data and return the data request in json format. getRequestDispatcher (url ). forward (request, response );

Method 4:

Use the src attribute of the iframe tag for cross-origin access, store the obtained value to the current iframe, and then obtain the value in the body of the iframe on the same page.

<Body> <div id = "show"> </div> <iframe id = "frame" style = "display: none; "> </iframe> </body> <script> $ (" # frame "). attr ("src", "path? Time = "+ new Date (). getTime ()). load (function () {// obtain and obtain the value of the iframe tag, which is displayed on the page $ ("# show "). append ("[data:" + $ ("# frame "). get (0 ). contentDocument ). find ("body "). text () + "]") ;}); </script>

Method 5:

In HTML5, websocket can be used for cross-origin access;

Create a websocket object:
Copy codeThe Code is as follows: var ws = new WebSocket (url );

The main event types are onopen, onclose, onmessage, and onerror );

For example:

Ws. onopen = function () {console. log ("open"); // send data to the background ws. send ("open ");}

The backend can be java, php, and nodejs. The returned value is processed by the onmessage event in time.

ws.onmessage = function(eve){console.log(eve.data);}

I hope this article will help you design javascript programs.

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.