A detailed example of js's implementation of cross domain methods

  • 2020-06-19 09:45:23
  • OfStack

This article gives an example of how js implements cross-domain implementation. Share to everybody for everybody reference. The specific analysis is as follows:

Due to the same-origin policy, XMLHttpRequest only allows requests for resources from the current source (including domain name, protocol, port).

Differences between json and jsonp:

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

The script tag is often used to load resources in different domains to bypass the same origin policy. (Those with src attribute can get exotic files).
If the requested remote data is itself a 1 piece of executable js, then these js are executed (equivalent to eval).

Method 1:

Request with the script tag ( < script src = "http: / /... jsp & # 63; callback= callback function name" > < /script > )
Before making a request using the script tag, make a declaration call to the callback function,


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

One of the simplest ways to pass javascript objects is to use JSON, which is called JSONP for cross-domain communication.

Remote server piece together string:

The callback function name ({" name1 ":" data1 ", "name2", "data2"})

The latter assembles THE json data and returns it to the client in the form of callback functions and parameters
(Can be called directly equivalent to the obtained string has been eval processing)

Such as:


function databack(data){ alert(data.name1) }
//  It will output the display "data1"

Method 2:

jquery makes it easier to implement exotic loading methods (same as ajax asynchronous requests)


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

Or the short form


var url = "http://.....jsp?callback=?";
//  in jquery Here in the callback It can be anything, 
//  because jquery After processing is used success The callback function accepts the data. 
$.getJSON( url, function(data){ alert(data.name1) });

Method 3:

ajax cross-domain server proxy

Set 1 agent in the same origin background (proxy. jsp...) ;
Interact with exotic servers on the server side.

jquery Reception Transmits data:

Such as:


$.get(
   'http:// . .jsp', //  Agent address 
   {
    name1 : "data1",
    name2 : "data2"
   },
   function(data){
   if(data == 1) alert(' Send successfully! ');
   }
);

Processing of background data:


String data1 = request.getParameter("name1");
........
//  Here the url For the other 1 Addresses under fields with parameters 
String url = "http://.....com/.../sss.jsp?" + "name1=" + data1+ "name2=" + data2;
//  Jump to the other 1 The fields are processed and returned json Formatted data 
request.getRequestDispatcher(url).forward(request,response);

Method 4:

Use the src attribute of the iframe tag to make cross-domain access, store the acquired value in the current iframe, and then obtain the value in the body of the iframe with the 1 page.


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

Method 5:

In HTML5, websocket can be accessed across domains.

Create 1 websocket object:

var ws = new WebSocket(url);

Main processing event type (onopen onclose, onmessage, onerror);

Such as:


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

The background can be java,php,nodejs, etc., the data processing time onmessage event to return the value of the front-end processing.


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

I hope this article has been helpful for your javascript programming.


Related articles: