JSONP cross domain principle analysis and its implementation

  • 2020-03-30 02:24:20
  • OfStack

JavaScript is a front-end dynamic scripting technique often used in Web development. In JavaScript, there is an important security restriction known as the "same-origin Policy". This policy imposes important restrictions on the content of the page that JavaScript code can access, meaning that JavaScript can only access content in the same domain as the document that contains it.

JavaScript is a security policy that is particularly important in multi-iframe or multi-window programming, and in Ajax programming. According to this policy, pages under baidu.com contain JavaScript code that cannot access the content of pages under the google.com domain name. Even pages between different subdomains cannot be accessed by JavaScript code. The impact on Ajax is that Ajax requests implemented through XMLHttpRequest cannot submit requests to different domains, for example, pages under abc.example.com, cannot submit Ajax requests to def.example.com, and so on.

However, the "same origin policy" is too demanding when doing some in-depth front-end programming that inevitably requires cross-domain operations. JSONP cross domain GET requests are a common solution. Let's take a look at how JSONP cross domain is implemented and explore the principles of JSONP cross domain.

Use create in the page < Script> Methods of nodes that submit HTTP requests to different domains are called JSONP, and this technique solves the problem of submitting Ajax requests across domains. JSONP works as follows:

Suppose in http://example1.com/index.php this page submit a GET request to http://example2.com/getinfo.php, we can put the following JavaScript code on this page http://example1.com/index.php to achieve:
 
var eleScript= document.createElement("script"); 
eleScript.type = "text/javascript"; 
eleScript.src = "http://example2.com/getinfo.php"; 
document.getElementsByTagName("HEAD")[0].appendChild(eleScript); 

When GET request returning from http://example2.com/getinfo.php, can return to a JavaScript code, this code will be executed automatically, can be used to is responsible for calling a callback function in http://example1.com/index.php pages.

JSONP has the advantage that it is not subject to the same origin policy as Ajax requests implemented with the XMLHttpRequest object. It is more compatible and works in older browsers without XMLHttpRequest or ActiveX support. The result can be returned after the request is completed by calling a callback.

The downside of JSONP is that it only supports GET requests and not 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.
Here's another example:
 
var qsData = {'searchWord':$("#searchWord").attr("value"),'currentUserId': 
$("#currentUserId").attr("value"),'conditionBean.pageSize':$("#pageSize").attr("value")}; 
$.ajax({ 
async:false, 
url: http:// cross-domain dns/document!searchJSONResult.action, 
type: "GET", 
dataType: 'jsonp', 
jsonp: 'jsoncallback', 
data: qsData, 
timeout: 5000, 
beforeSend: function(){ 
//This method is not triggered because the dataType is no longer an ajax event if it is specified as jsonp
}, 
success: function (json) {//The client-side jquery predefined callback function, which is dynamically executed after successful retrieval of the json data on the cross-domain server
if(json.actionErrors.length!=0){ 
alert(json.actionErrors); 
} 
genDynamicContent(qsData,type,json); 
}, 
complete: function(XMLHttpRequest, textStatus){ 
$.unblockUI({ fadeOut: 10 }); 
}, 
error: function(xhr){ 
//This method is not triggered because the dataType is no longer an ajax event if it is specified as jsonp
//Request error handling
alert(" Request error ( Please check the status of the relevancy network .)"); 
} 
}); 
 Sometimes you'll see it written like this:  
$.getJSON("http:// cross-domain dns/document!searchJSONResult.action?name1="+value1+"&jsoncallback=?", 
function(json){ 
if(json. The property name == value ){ 
//Execute the code
} 
}); 

This is actually the above example $.ajax({.. }) a high-level encapsulation of the API in which some of the underlying parameters of the $.ajax API are encapsulated and not visible.
In this way, jquery will assemble the following url get request:
 
http:// cross-domain dns/document!searchJSONResult.action?&jsoncallback=jsonp1236827957501&_=1236828192549&searchWord= 
%E7%94%A8%E4%BE%8B because tUserId=5351&conditionBean.pageSize=15 

On the response side (http:// cross-domain DNS /document! SearchJSONResult. Action), Jsoncallback = request-getparameter ("jsoncallback") to get the js function name:jsonp1236827957501 that the jquery end will callback later, and then the response content is a Script Tags:"jsonp1236827957501("+ json array generated by request parameter +")". Jquery calls the js tag:jsonp1236827957501(json array) dynamically through the callback method. This achieves the purpose of cross - domain data exchange.

The json principle
The most basic principle of JSONP is: add a < Script> The SRC attribute of a script tag has no cross-domain restrictions. In this case, this cross-domain approach has nothing to do with the ajax XmlHttpRequest protocol.
This makes "jQuery AJAX cross-domain problem "a pseudo-proposition. The name of the jQuery $. AJAX method is misleading.
If you set it to dataType: 'jsonp', the $.ajax method has nothing to do with the ajax XmlHttpRequest and is replaced by the jsonp protocol. JSONP is an unofficial protocol that allows for server-side integration of Script tags back to the client, with cross-domain access in the form of javascript callback.

JSONP is JSON with Padding. Because of the same origin policy, XmlHttpRequest is only allowed to request resources from the current source (domain name, protocol, port). If we want to make a cross-domain request, we can make the cross-domain request by using the script markup of the HTML and returning the script code to execute in the response, where we can pass the javascript object directly using JSON. This cross-domain communication is called JSONP.

JsonCallback function jsonp1236827957501 (...). : a function that is registered by the browser client and called back after it gets the json data on the cross-domain server

The execution process of Jsonp is as follows:
A callback (such as 'jsoncallback') is registered on the client side, and the name of the callback (such as jsonp1236827957501) is passed to the server. Note: after the server gets the value of the callback, use jsonp1236827957501(...) By including the json content to be output, the server can generate the json data to be received correctly by the client.

Then, in javascript syntax, generate a function whose name is the value of the passed parameter 'jsoncallback' jsonp1236827957501.
Finally, the json data is directly placed into the function in the form of input, so that a js syntax document is generated and returned to the client.

The client browser parses the script tag and executes the returned javascript document, at which point the javascript document data, as a parameter, is passed to the client's predefined callback function (success: function (json) encapsulated by the jquery $.ajax() method in the example above).
You could say that the way jsonp works is in principle the same as < Script SRC ="http:// cross-domain /... Xx. Js "> < / script> Is consistent (qq space is a large number of this way to achieve cross-domain data exchange). JSONP is a Script Injection behavior, so it has some security risks.
So why doesn't jquery support post across domains?

Although post+ dynamic generation of iframe can achieve the purpose of post cross-domain (a js awesome person just made patch of jquery1.2.5 in this way), it is a relatively extreme way and is not recommended.
It can also be said that the cross-domain of get method is legal, and the post method is considered illegal from the perspective of security. Therefore, it is better not to go astray.

The need for cross-domain access on the client side also seems to have caught the w3c's attention. According to sources, the html5 WebSocket standard supports cross-domain data exchange and should be an alternative cross-domain data exchange solution in the future.

Here's a super simple example:
 
<!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>Test Jsonp</title> 
<script type="text/javascript"> 
function jsonpCallback(result) 
{ 
alert(result.msg); 
} 
</script> 
<script type="text/javascript" src="http://crossdomain.com/jsonServerResponse?jsonp=jsonpCallback"></script> 
</head> 
<body> 
</body> 
</html> 

Among them, jsonCallback is a function that is registered by the client and called back after obtaining the json data on the cross-domain server. http://crossdomain.com/jsonServerResponse? Jsonp =jsonpCallback this url is the interface to fetch json data from the cross-domain server. The parameter is the name of the callback function, and the format of the return is: jsonpCallback({MSG :'this is json data'}).

Briefly describe the principle and procedure: first, a callback is registered on the client side, and then the name of the callback is passed to the server. At this point, the server generates json data. Then, in javascript syntax, generate a function whose name is the parameter jsonp passed in. Finally, the json data is directly placed into the function in the form of input, so that a js syntax document is generated and returned to the client.

The client browser parses the script tag and executes the returned javascript document, with the data passed as a parameter to the client's predefined callback function. (dynamically executing callback functions)

Related articles: