JS JSOP Cross Domain Request Instance Explanation

  • 2021-07-01 06:42:22
  • OfStack

Cross-domain problems encountered in project development are generally solved through JSONP. But what exactly is JSONP and what is the principle of implementation? In the free time of the project, you can study it well.

1. What is JSONP?

To understand JSONP, we have to mention JSON, so what is JSON?

JSON is a subset of the object literal notation of JavaScript. Since JSON is a subset of JavaScript, it can be used in the language with no muss or fuss.

JSONP (JSON with Padding) is an unofficial protocol that allows Script tags to be integrated on the server side and returned to the client side, and cross-domain access is realized in the form of javascript callback (this is only a simple implementation form of JSONP).

2. What's the use of JSONP?

Due to the restriction of homologous policy, XmlHttpRequest only allows to request the resources of the current source (domain name, protocol, port). In order to realize cross-domain request, cross-domain request can be realized through script tag, and then JSON data is output at the server and callback function is executed, thus solving cross-domain data request.

Generation of JSONP

1. As we all know, the resources requested by Ajax are limited by the same domain, whether it is static resources, dynamic pages or web services

2. At the same time, we found that the web page invokes the JS file without cross-domain effects (not only that, we also found that any tag with the attribute 'src' has cross-domain capabilities, such as < script > , < img > , < iframe > Etc.)

3. It is conceivable that at the present stage, if you want to access data across domains through web (ActiveX control, server agent, websocket of HTML5, etc.), there is only one possibility, that is, the server loads the data into JS format files for the client to call and process

4. Data transmission, we know that a pure character data format called JSON can describe complex data structure concisely, and it is also supported by JS, so it is easy to deal with data in this format at the client

5. In this way, the solution is clear. The web side calls the dynamically generated JS file on the cross-domain server in the same way as the calling script. The server needs to dynamically generate JS file, the purpose is to obtain the callback function name of the client and transfer the data needed by the client through JSON (also can be pure string) format

6. After the client calls the JS file successfully, it gets the parameters in the callback function, and the rest is the data processing. This method looks very similar to Ajax, but it is not like 1 (Jquery encapsulates JSONP and Ajax in 1, if people who don't understand it will be mixed with 1)

7. In order to facilitate the client to use the data, One of the key points of this protocol is to allow the user to pass an callback parameter to the server, and then the server will use this callback parameter as a function name to wrap the JSON data when returning data, so that the client can customize its own function to process the returned data automatically

Well, I don't know if you understand JSONP. If not, I will come out and summarize it. If it is not good, don't hit me.

In fact, the principle is, The client requests a link, And add the required parameters, callback means that it is a request of JSONP (the front-end and background can be unified by themselves). The background analyzes this request link and finds that it is a request of JSONP, then generates a call method, and dynamically generates a string (which can be JSON or pure string) according to the request parameters and stuffs it into the call method, so that the client can get the data and do subsequent processing.

Having said so much, it's not my style not to code, but to code. .


function test(data){
console.log(data)
}
var url="http://www.x.com/test?a=1&callback=test"// Toward x.com/test Transfer parameter a Value is 1 And tell him that the name of the function to call is " test " 
// Background interception to callback Knowing that you want to generate 1 Call method with the name of test And pass the parameters, and the background processing generates the following (data fiction) 
test("aaaaaa")
test({a:1,b:2})
// Then the front end passes through script Tag to access and execute the above things 
var script = document.createElement('script');
script.setAttribute('src', url);
//  Put script Tag addition head At which point the call begins 
document.getElementsByTagName('head')[0].appendChild(script); 
// Then the page's test Method, this is jsonp The realization principle of. 

Reality of JSONP in Jquery


$.ajax({
type: "GET",
url: "http://x.d.cn/asych/adv.html?loc=8&callBack=?",// Tell the backstage that this is 1 A jsonp Request, what method need to be called, if "?" , jq Will automatically generate it for you (if you use jq1 Is generally set to "?" To trigger on success jq Callback function of) 
type:"post",//jsonp Send only get Request, even if I set the request type to post
dataType:"jsonp",// Tell jquery This is 1 A jsonp Data that needs to be generated script Tag to load js
data:{
a:"1"
},
/*success: function (data) {// After success jq The method that will be executed if callback Parameter is "?") 
$("body").append(data);
},*/
error: function (XMLHttpRequest, textStatus, errorThrown) {
//alert(errorThrown);
}
}).done(function(data){
$("body").append(data);
});

After reading the above code and comments, I believe everyone understands that although Jquery encapsulates JSONP into Ajax, it is essentially different.

The core of Ajax is to get non-page content through XmlHttpRequest, while the core of JSONP is to add dynamically < script > Tag to call the js script provided by the server.

Therefore, the difference between Ajax and JSONP is not whether it is cross-domain. Ajax can realize cross-domain through server proxy 1, and JSONP itself does not exclude the acquisition of data in the same domain.

As mentioned above, the data format of JSONP and Ajax is either JSON or pure string.

In a word, JSONP is not a subset of Ajax, and even if Jquery encapsulates JSONP into Ajax, this point cannot be changed.


Related articles: