Writing in the front

Jsonp (JSON with Padding) is the first thing that comes to mind when talking about javascript cross-domain. What is the implementation principle of this cross-domain mode? I admit THAT I have used it for a long time, but it is only now that I know, so it is….

If I access the interface under api.com locally, there will be a cross-domain request problem. Why can JSONP solve this problem?

  • 1. What does the script tag load?

SRC to load the js script, write the address of the script, and the browser will load it.

  • 2, so localjsonp.htmlThe script tag can be loadedapi.comThe domain name below the script file?

B: yes, you can! Otherwise, those who use CDN to optimize the loading speed of web pages are unlikely to succeed

<script type="text/javascript" src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
Copy the code
  • 3, then script can load other domain name under the script file, andjsonpGan?

As we all know, it is ok to load js scripts under the api.com domain name. In this case, the JS script files under the API.com are real static resources. What if the script file is generated by a back-end language? Example use PHP ==>jsonp.php


      
 echo 'alert("Hello world")';
? >
Copy the code
  • PHP file, how to load this script?

The answer is: our script tag is capable of loading.php files, i.e

<script type="text/javascript" src='http://localhost/jsonp.php'></script>
Copy the code

The results

As the above shows, it is possible to generate a script on the server side, and then load the HTML page with the script tag and execute the script.

So, can we execute the methods defined in THE HTML in the generated script? Let’s try it out

index.html

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>jsonp</title>
</head>
<body>
</body>
<script type="text/javascript">
  function execWithJsonp(para){
    console.log('I was executed by a script in jsonp.php, passing in the argument ==>'+para);
    console.log(para)
  }
</script>
<script type="text/javascript" src='http://localhost/jsonp.php'></script>
</html>

Copy the code

jsonp.php


      
 echo "execWithJsonp({status:'ok'})";
? >
Copy the code

The results

Yes, we found that it was totally fine. We usually call the interface to get the data back from the back end. In the example above, the back end generates the script with the parameters already passed to us.

Question: If the back-end interface is written this way, wouldn’t the front end define a execWithJsonp method everywhere the interface is called?

If the page is called twice and the processing logic is different, don’t we have to distinguish which one is called? I want to call a different data processing function each time I access the interface, and each time I tell the back end which function to use to process the returned data. Sure, we can do that

index.html

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>jsonp</title>
</head>
<body>
</body>
<script type="text/javascript">
  function execWithJsonp(para){
    console.log('I'm executed by a script in jsonp.php, I'm execWithJsonp, and the argument I pass in is ==>'+para);
    console.log(para)
  }
  function doExecJsonp(para){
    console.log('I'm executed by a script in jsonp.php, I'm doExecJsonp, and the argument passed in is ==>'+para);
    console.log(para)
  }
</script>
<script type="text/javascript" src='http://localhost/jsonp.php? callback=doExecJsonp'></script>
<script type="text/javascript" src='http://localhost/jsonp.php? callback=execWithJsonp'></script>
</html>
Copy the code

jsonp.php


      
  $callback=$_GET['callback'];
  echo $callback."({status:'ok'})";
? >
Copy the code

The results

At this point, I still don’t seem to say what the principle is, in fact, you will understand after reading the above

Jsonp is actually

  • 1. The data processing function passed to the back-end when the front-end calls the back-endcallback
  • 2. Back-end receive processing functioncallbackThen, perform database query and other operations, and put the data (usually in JSON format) to be transferred from the back end to the front endcallbackFunction of the(a)And return a javascript script that is dynamically generated by the back end and available to the front end.
  • 3. The HTML page automatically executes the script after the script file is loaded
  • 4. Complete the entire JSONP request.

The advantages and disadvantages

Advantages: It is not restricted by the same origin policy as Ajax requests implemented by the XMLHttpRequest object; It is more compatible, runs in older browsers and does not require XMLHttpRequest or ActiveX support; After the request is complete, the result can be returned by calling callback.

Disadvantages: It only supports GET requests and does not support other types of HTTP requests such as POST. It only supports cross-domain HTTP requests and does not solve the problem of how to make JavaScript calls between two pages in different domains, which obviously requires the cooperation of back-end engineers.

Postscript, use your imagination, see this thing how to operate

 function execWithJsonp(para){
    console.log('I'm executed by a script in jsonp.php, I'm execWithJsonp, and the argument I pass in is ==>'+para);
    console.log(para)
  }
  function doExecJsonp(para){
    console.log('I'm executed by a script in jsonp.php, I'm doExecJsonp, and the argument passed in is ==>'+para);
    console.log(para)
  }

doJsonp('doExecJsonp')

function doJsonp(callbackName){
  var script=document.createElement('script');
  script.src='http://localhost/jsonp.php? callback='+callbackName;
  document.body.appendChild(script);
}
Copy the code