5 solutions for js cross domain requests

  • 2020-06-22 23:52:20
  • OfStack

Cross-domain request data solutions mainly include the following solutions:


JSONP way 
 The form POST way 
 Server agent 
Html5 the XDomainRequest
Flash request

Separate instructions:

1. JSONP:

Intuitive understanding:

Is to dynamically register a function on the client side

function a(data), then passes the function name to the server, which returns 1 a({/*json*/}) to the client to run, thus calling the client

function a(data), thus achieving cross-domain.

Birth Background:

1. There is the problem that ordinary files directly requested by Ajax have no right to access across domains, no matter whether they are static pages, dynamic pages, web services or wcf.

2. However, the js file is not affected when it is called on an web page

3. After further promotion, we found that all tags with Src attribute have cross-domain capability, such as: < script > < img > < iframe >

4. Thus, for the time being, if you want to access data across domains via pure web (ActiveX controls, server-side proxies, Websocket belonging to the future HTML5, and so on don't count), you have to try to get the data into js formatted text on a remote server for the client to call and step forward.

5, JSON is a pure character data format, and can be js native support.

6. The solution is thus developed: the web client invokes the dynamically generated js format file on the cross-domain server (1 is usually suffixes with json) in the same way as the invocation script 1.

7. After the client successfully calls the json file, it gets the required data, and the rest is processed according to its own requirements.

8 To facilitate the use of data by clients, an informal transport protocol, called jsonp, has been gradually formed. One of the key features of the protocol is that it allows the user to pass an callback parameter to the server, and then the server returns the callback parameter as the function name to wrap the json data so that the client can customize its own function to handle the returned data.

Specific implementation:

Whether it's jQuery, extjs, or any other framework that supports jsonp, what they're doing behind the scenes is the same. Here's a step-by-step description of how jsonp is implemented on the client side:

1. We know that web pages can be executed unconditionally even if the code in a cross-domain js file is compliant with the web script security policy, of course.

The remote server remoteserver. com root directory has an ES88en. js file code as follows:

alert(' I'm a remote file ');

The local server localserver. com has jsonp. html page code as follows:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title></title>
  <script type="text/javascript" src="http://remoteserver.com/remote.js"></script>
</head>
<body>

</body>
</html>

Without a doubt, the page will pop up a prompt showing that the cross-domain call was successful.

2. Now we define a function on the jsonp.html page, and then pass in the data in the remote ES1064en.js to make the call.

jsonp. html page code is as follows:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title></title>
  <script type="text/javascript">
  var localHandler = function(data){
    alert(' I'm a local function that can be cross-domain remote.js File call, remote js The data is as follows: ' + data.result);
  };
  </script>
  <script type="text/javascript" src="http://remoteserver.com/remote.js"></script>
</head>
<body>

</body>
</html>

remote. js file code is as follows:

localHandler({"result":" I am the data from remote js "});
After running, the page pops up a prompt that shows that the local function was successfully called by the remote js across the domain and that the data brought by the remote js has been received. Happily, the goal of getting data remotely across domains is basically achieved, but another problem arises: how do I let remote js know the name of the local function it is supposed to call? After all, the server of jsonp faces many service objects with different local functions. Let's move on.

3, smart developers, it's easy to think of, as long as the server provides js scripts are dynamically generated line bai, so that the caller can pass a parameter in the past told the service side "I want 1 piece XXX function called js code, please return to me", then the server can according to client's demand to generate js script and response.

Look at the jsonp. html page code:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title></title>
  <script type="text/javascript">
  //  Get the flight information query results after the callback function 
  var flightHandler = function(data){
    alert(' The flight result you checked is: fare  ' + data.price + '  Yuan, ' + ' More ticket  ' + data.tickets + '  Zhang. ');
  };
  //  provide jsonp The service of url Address (Whatever the type of address, the resulting return value will be 1 Period of javascript Code) 
  var url = "http://flightQuery.com/jsonp/flightResult.aspx?code=CA1998&callback=flightHandler";
  //  create script Tag, which sets its properties 
  var script = document.createElement('script');
  script.setAttribute('src', url);
  //  the script Label to join head , when the call starts 
  document.getElementsByTagName('head')[0].appendChild(script); 
  </script>
</head>
<body>

</body>
</html>

Instead of writing the remote js file to death, the code implements dynamic query, which is the core part of the jsonp client implementation. In this case, the focus is on how to complete the whole process of jsonp invocation.

We see that the call to url passes an code parameter, telling the server that I'm looking for flight CA1998, and the callback parameter tells the server that my local callback function is called flightHandler, so please pass the query result into this function to make the call.


flightHandler({
  "code": "CA1998",
  "price": 1780,
  "tickets": 5
});

We see that what is passed to the flightHandler function is an json, which describes the basic information of the flight. Run the following page and the prompt window pops up successfully. The whole process of jsonp is completed successfully!

4, so far, I believe you have been able to understand the jsonp client implementation principle? All that remains is how to wrap the code under 1 so that it can interact with the user interface for multiple and repeated calls.

What? You're using jQuery, wondering how jQuery implements jsonp calls? Ok, I'll stick it out and give you one more piece of jQuery using jsonp (we'll stick with the flight information query example above, assuming we return jsonp the same) :

OK, the server is very clever, this page called ES170en.aspx generates a piece of code like this for ES172en.html (the implementation of the server is not demonstrated here, it doesn't depend on your language of choice, it is just a concatenation of strings) :


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml" >
 <head>
   <title>Untitled Page</title>
   <script type="text/javascript" src=jquery.min.js"></script>
   <script type="text/javascript">
   jQuery(document).ready(function(){ 
    $.ajax({
       type: "get",
       async: false,
       url: "http://flightQuery.com/jsonp/flightResult.aspx?code=CA1998",
       dataType: "jsonp",
       jsonp: "callback",// Passed to a request handler or page for retrieval jsonp The argument name of the callback function name (1 As the default for :callback)
       jsonpCallback:"flightHandler",// The custom of jsonp Name of the callback function, default jQuery Automatically generated random function name, can also be written "?" . jQuery It will automatically process the data for you 
       success: function(json){
         alert(' You can check the flight information: Ticket price:  ' + json.price + '  Yuan, balance:  ' + json.tickets + '  Zhang. ');
       },
       error: function(){
         alert('fail');
       }
     });
   });
   </script>
   </head>
 <body>
 </body>
 </html>

Isn't that a little weird? Why didn't I write flightHandler this time? And it worked! When jQuery handles ajax of the type jsonp (although, ironically, jquery also includes jsonp as ajax, they are not really one thing), it automatically generates callback functions for you and pulls the data out for the success attribute method to call, isn't that nice?

This is the end of this article, I hope you enjoy it.


Related articles: