javascript implements cross domain method aggregation

  • 2020-06-19 09:48:48
  • OfStack

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  Callback function name ( 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 json data and returns it to the client in the form of callback function data transfer parameters
(Can be called directly equivalent to the string has been obtained eval processing)
For example: function databack(data){alert(data. name1)} // will output "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 & # 63; callback = & # 63;" ; // In jquery the value of callback here can be arbitrary because

After processing, jquery USES the callback function of success to accept the data.
$.getJSON( url, function(data){ alert(data.name1) });

Method 3:

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

jquery Front-end data transmission:
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 for cross-domain access, store the acquired value in the current iframe, and then again

Get the value in 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:

HTML5 allows cross-domain access to websocket;
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 of onmessage event to return the value of the front-end processing.


    ws.onmessage = function(eve){

      console.log(eve.data);

    }


Related articles: