Home >Web Front-end >JS Tutorial >Summary of methods for cross-domain implementation in javascript_javascript skills

Summary of methods for cross-domain implementation in javascript_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:52:481222browse

Due to the restrictions of the same-origin policy, XMLHttpRequest is only allowed to request resources from the current source (including domain name, protocol, and port).

The difference 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 from different domains and can bypass the same-origin policy. (Anyone with the src attribute can obtain foreign files).
If the requested remote data itself is an executable js, then these js will be executed (equivalent to eval).

Method 1:

Use script tag to request (78010db0eb808838eba79e088e2901192cacc6d41bbb37262a98f745aa00fbf0)
Before using the script tag to request, first declare the callback function,

  <script>
    function 回调函数名(data数据){  。。。。 }
  </script>
  <script src="http://....jsp&#63;callback=回调函数名"></script>

Using JSON to transfer javascript objects is the simplest way. This cross-domain communication method is called JSONP.
 
Remote server piece together string:
Callback function name ({"name1":"data1","name2","data2"})
This kind of json data is pieced together in the background and returned to the client using the callback function to pass parameters
(You can call it directly, which is equivalent to eval processing the obtained string)
For example: function databack(data){ alert(data.name1) } // Will output and display "data1"

Method 2:

It is simpler to implement the foreign loading method with jquery (the same as the asynchronous request method of ajax)

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

or abbreviated form
var url = "http://.....jsp?callback=?"; // The callback value here in jquery can be arbitrary, because

After jquery is processed, the success callback function is used to accept data;
$.getJSON( url, function(data){ alert(data.name1) });

Method three:

Ajax cross-domain server proxy
Set up a proxy program (proxy.jsp...) in the background of the same origin; interact with the server in a foreign domain on the server side.
 
jquery frontend data transmission:
For example:

    $.get(
      'http://。。。.jsp',  // 代理程序地址
      {
         name1 : "data1",
         name2 : "data2"
       },
       function(data){
      if(data == 1) alert('发送成功!');
       }
    );
  

Background data processing:

    String data1 = request.getParameter("name1");
    ........
    // 此处的url为另一域下的地址并带有参数
    String url = "http://.....com/.../sss.jsp&#63;" + "name1=" + data1+ "name2=" + 

data2;
    // 跳转到另一个域进行数据的处理并返回json格式的数据
    request.getRequestDispatcher(url).forward(request,response);

Method 4:

Use the src attribute of the iframe tag to perform cross-domain access, store the obtained value in the current iframe, and then

Get 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", "路径&#63;time=" + new Date().getTime()).load(function(){
  // 获取iframe标签的值并进行获取,显示到页面
  $("#show").append("[data: " + $($("#frame").get(0).contentDocument).find("body").text() 

+ " ]");
});
  </script>

Method 5:

Websocket in HTML5 can provide cross-domain access;
Create a websocket object:

 var ws = new WebSocket(url);

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

For example:

    ws.onopen = function(){

      console.log("open");

      // 向后台发送数据

      ws.send("open");

    }

The background can be java, php, nodejs, etc. For data processing, use the time onmessage event to perform front-end processing on the returned value.

    ws.onmessage = function(eve){

      console.log(eve.data);

    }

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn