Explanation of JSONP Cross Domain Request Instance

  • 2021-07-01 06:41:18
  • OfStack

Introduction to JSOP

JSONP (JSON with Padding) is a "usage mode" of JSON, which can be used to solve the problem of cross-domain data access of mainstream browsers. Because of the homology policy, 1 generally, a web page located at server1.example. com cannot communicate with a server that is not server1.example. com, while HTML's < script > Element is one exception. Utilization < script > Element, Web pages can get dynamically generated JSON data from other sources, and this usage pattern is called JSONP. The data captured by JSONP is not JSON, but arbitrary JavaScript, which is executed by JavaScript literal translator instead of parsed by JSON parser.

There are many ways to request across domains:

1.iframe
2.document.domain
3.window.name
4.script
5.XDomainRequest (IE8+)
6.XMLHTTPRequest (Firefox3.5+)
7.postMessage (HTML5)
8. Background Agent
9....

They have their own advantages and disadvantages, and the data formats returned are also different, so they should be carefully selected according to their needs. For example, it is more suitable for iframe to return html fragment, and it is not worth the loss to use it to return JSON. At the beginning of this article, I will build a practical cross-domain request tool Sjax. The biggest drawback and challenge of using script requests is error handling. For example, 404 error, which does not return the status code 404 accurately like XMLHTTPRequest. I put this in the last article.

This series mainly describes Mode 4 listed above, that is, returning data in JSON format through script. This method is now called JSONP. JSON is one of the most popular and widely used formats for front-end and back-end communication. Compared with the early AJAX returning XML (X in AJAX is XML), JSON is lightweight, without redundant Tag tags, and its parsing is native. After XML returns to the front end, it is first converted into a document, which is parsed by DOM API1 layers. Parsing DOM is expensive, especially in the early version of IE (IE6/7/8), and the communication between core js and dom is very expensive.

The implementation of JSONP is simple

1. The front end creates the script tag, sets src, and adds it to head (you can add it to body)

2. One js variable jsonp is returned in the background, and this jsonp is the requested JSON data

3. Remove the script tag after the callback is completed (there is also some cleaning work such as avoiding some browser memory leaks, etc.)

Interface


Sjax.load(
url, //  Across the request URL
success, //  Callback function, you must define 1 A formal parameter for receiving global variables returned from the background jsonp  (The convention is that the background returns such as jsonp = {...} Structure) 
timestamp, //  Biography true Will add 1 A timestamp, prevent caching, and do not add it by default 
); 

Example:


<!DOCTYPE HTML>
<html> 
<head> 
<meta charset="utf-8"> 
<title>sjax_0.1.js by snandy</title>
<script src="http://files.cnblogs.com/snandy/sjax_0.1.js"></script>
</head> 
<body>
<p id="p1" style="background:gold;"></p>
<input type="button" value="Get Name" onclick="clk()"/>
<script type="text/javascript">
function clk(){
Sjax.load(
'http://files.cnblogs.com/snandy/jsonp.js', 
function(){
document.getElementById('p1').innerHTML = 'Hi, ' + jsonp.name;
}
); 
}
</script>
</body>
</html> 

This html realizes the simplest front-end and back-end interaction function. Click the button "Get Name", get name and display it on paragraph P.

The Sjax. load method is called in the clk function, and S in Sjax refers to script. I used the name Ajax in my previous Ajax series, and here I use Sjax.

The background url of the request is jsonp. js, which returns the following


jsonp = {name:'jack'}; 

Because it is a test, it is implemented in the simplest way here. In fact, the background of the request does not need to be js file, but can be any background language such as php and java, which may connect to the database for 1 series of business queries. In short, the last structure it returns must be the variable jsonp, which is an js object. It is not necessary to pay attention to how complex it is.


Related articles: