JS Jsop cross-Domain Request example detailed _javascript skills

Source: Internet
Author: User
Tags script tag domain server

In the project development encountered Cross-domain problems, generally through JSONP to solve. But what is JSONP, and what is the principle of realization? The free time of the project can be well studied.

1, what is JSONP?

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

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

JSONP (JSON with Padding) is an unofficial protocol that allows the server-side integration script tags to be returned to the client and Cross-domain access through JavaScript callback (this is simply a JSONP form of implementation).

2. What is the use of JSONP?

Due to the restriction of the homology policy, XMLHttpRequest only allows resources to request the current source (domain name, protocol, port), and in order to implement Cross-domain requests, Cross-domain requests can be implemented through the script tag, and then the JSON data and the callback function are executed on the server, thus resolving cross-domain data requests.

The generation of JSONP

1. It is well known that AJAX requests resources are constrained by the same domain, whether static resources, dynamic pages, Web services are not

2. At the same time we found that the Web page calls JS file is not affected by cross-domain (not only that, we also found that all of the ' src ' attribute of the tag has cross-domain capabilities, such as <script>, , <iframe>, etc.)

3. It is conceivable that the current phase if you want to access data across domains through the web side (ActiveX control, Server Agent, HTML5 websocket, etc.) there is only one possibility, that is, the server-side data into the JS format file for client invocation and processing

4. Data transmission, we know that a simple character data format called JSON can be concise description of complex data structure, but also be JS native support, in the client can easily handle this format of data

5. This solution at a glance, the web side through and call the script exactly the same way, to invoke the dynamically generated JS file across the domain server. The reason why the server is dynamically generating JS files is to obtain the callback function name of the client and pass the data required by the client through JSON (or a pure string) format.

6. After the client to the JS file call success, but also get the callback function in the parameters, the rest is the processing of data, this method and Ajax look like, but not the same (jquery will JSONP and Ajax packaged together, if not understand the people will be confused)

7. In order to facilitate the use of data by clients, an informal transport protocol has been developed, which is called JSONP, and one of the key points of this protocol is to allow the user to pass a callback parameter to the server, The service side then returns the data by wrapping the callback parameter as the function name to wrap the JSON data so that the client can customize its own function to automatically process the returned data.

Well, do not know that we understand the JSONP did not, if not, I will come out to sum up, said the bad, do not hit me.

In fact, the principle is that the client requests a link, and the required parameters Plus, callback is a JSONP request (this front-end and the background can be unified), the background parsing the request link, found to be a JSONP request, and then generate a call method, and dynamically generate a string (either JSON or pure string) based on the request parameters into the calling method so that the client can get to the data and do the post-processing.

Said so much, not on the code is not my style ah, on the code.

function test (data) {
console.log (data)
}
var url= "http://www.x.com/test?a=1&callback=test"// Pass the parameter a value of 1 to the x.com/test and tell him that the function name to call is "test"
//Background intercept to callback, know to generate a calling method, the method name is test, and pass the parameter, the background processing generates the following (data fictitious)
test ( "AAAAAA")
Test ({a:1,b:2})
//Then the front end is accessed and executed through the script tag, the thing above
var script = document.createelement (' script ');
Script.setattribute (' src ', url);
Add the script tag to the head, at which point the call begins
document.getElementsByTagName (' head ') [0].appendchild (script); 
Then you will call the test method of the page, which is the principle of JSONP implementation.

About the reality of JSONP in jquery

$.ajax ({
type: "Get",
URL: "http://x.d.cn/asych/adv.html?loc=8&callBack=?",//tell the background this is a JSONP request, What method needs to be called, if "? ", JQ will help you generate automatically (if using JQ is generally set to"?) "To trigger the JQ callback function on success)
type:" Post ",//jsonp can only send get requests, even if I set the request type to post
dataType:" Jsonp ",// Tell jquery this is a JSONP data that needs to generate a script tag to load JS
data:{
A: "1"
},
/*success:function (data) {// What is the JQ method (if callback parameter is "?) after success. ")
$ (" Body "). Append (data);
},*/
error:function (XMLHttpRequest, Textstatus, Errorthrown) {
// alert (Errorthrown);
}
}). Done (function (data) {
$ (' body '). Append (data);

Looking at the code and comments above, I'm sure you all understand that while jquery encapsulates Jsonp into Ajax, it's essentially different.

The core of Ajax is to get non-page content through XMLHttpRequest, and the core of JSONP is to dynamically add <script> tag to invoke the JS script provided by the server.

So the difference between Ajax and JSONP is not whether Cross-domain, Ajax through the server-side proxy can be implemented across the domain, JSONP itself does not exclude the acquisition of the same domain data.

As mentioned above, the data formats for JSONP and Ajax are not necessarily JSON, but can also be pure strings.

In short, JSONP is not a subset of Ajax, and even if jquery encapsulates Jsonp into Ajax, it cannot change that.

The above is a small set to introduce the JS Jsop cross-domain request examples of detailed, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.