Ajax jsonp cross-origin request implementation method,
What is cross-origin?
Simply put, for security reasons, JavaScript on the page cannot access data on other servers, that is, "same-origin policy ". Cross-origin means to bypass the same-origin policy restrictions in some ways to achieve communication between different servers.
The following table lists the specific policy restrictions:
URL |
Description |
Allow communication |
Http://www.a.com/a.js Http://www.a.com/ B .js |
Under the same domain name |
Allow |
Http://www.a.com/lab/a.js Http://www.a.com/script/ B .js |
Different folders under the same domain name |
Allow |
Http://www.a.com: 8000/a. js Http://www.a.com/ B .js |
Different ports for the same domain name |
Not Allowed |
Http://www.a.com/a.js Https://www.a.com/ B .js |
Different protocols for the same domain name |
Not Allowed |
Http://www.a.com/a.js Http: // 127.0.0.100/B. js |
Corresponding ip addresses of domain names and domain names |
Not Allowed |
Http://www.a.com/a.js Http://script.a.com/ B .js |
The primary domain is the same and the subdomain is different. |
Not Allowed |
Http://www.a.com/a.js Http://a.com/ B .js |
Same domain name, different second-level domain names (same as above) |
Not Allowed |
Http://www.a.com/a.js Http://www. B .com/ B .js |
Different domain names |
Not Allowed |
What is JSONP?
JSON (JavaScript Object Notation) is a lightweight data exchange format, while JSONP (JSON with Padding) is a "usage mode" of JSON ", this mode can be used to obtain data across domains.
JSONP cross-origin principle
In the same-origin policy, data outside the server cannot be obtained on a page under a server, but labels such as img, iframe, and script are exceptions, these tags can request data from other servers through the src attribute. Using the open policy of the script tag, we can implement cross-origin request data. Of course, we also need the cooperation of the server. When we normally request a JSON data, the server returns a string of JSON data, and we use the JSONP mode to request data, the server returns an executable JavaScript code.
Cross-origin:Javascript has a single-source restriction. In short, different sources cannot interact with each other. so how to calculate the source is different? For example, if you access the server through A browser, you can only access the resources of server A (with the same domain name and port, in addition, the domain name and the corresponding ip address are not the same, either both domain names or ip addresses ).
The above is the cross-origin issue of js, but here we need to note that server A has no cross-origin issue. This problem only exists in js, that is: in js --> server A ---> Cross-origin resource in page A, this path is OK. this path is unavailable only for js ---> Cross-origin resources in page.
Let's talk about the jsonp in the solution. This is not a format, but a solution.
Jsonp principle: Although JavaScript has single-source restrictions, this restriction is not imposed when js files are introduced, that is:
<script type="text/javascript" src="xxx/xxxx.js"></script>
When the src attribute is introduced into the js file, there is no same-source restriction. In this case, external resources can be introduced. the principle of jsonp is here. By dynamically creating more than one line of js import statements, it uses its src attribute to access out-of-domain resources. the external resource server can return a string that can be parsed as a js statement, as shown in the following figure:
callback({"key":"value",...})
Among them, callback is the name that needs to be specified in advance. The green part is to return to the json string, and then splice it into the above form to return directly. in this way, after js receives the concatenated string from the server, it will directly execute the local js method named callback, Which is why callback needs to be agreed in advance, make sure that this js method exists on the page side. The parameter passed in by this method is the return value on the server side.
Ajax supports jsonp, so the above troubles will be done for us, written as follows:
$.ajax({ type: 'GET', url: "http://127.0.0.1:8080/xxx/xxx", async: false, dataType: "jsonp", jsonp: "callback", success: function(result){ ..... }, timeout:3000 });
The red text marks the call using the jsonp method. In fact, this is not a get request in the traditional sense. The actual implementation method is what we mentioned above. the callback in the red part is the part that we want to communicate with the server. This request is sent to the server, in fact:
Http: // 127.0.0.1: 8080/xxx? Callback = jqueryxxxx
The server must use callback (similar to request. getParameter ("callback"), that is, take the automatically generated values such as jqueryxxxx. This value is actually the success callback method in the ajax method in which the request is sent, if the server returns
jqueryxxxx({"ret":"ok"})
The success method is automatically executed on the page, and {"ret": "OK"} is passed to the result parameter of the success method.
The above is the process of implementing cross-origin access through jsonp through ajax. We can see that no additional operations are needed, and all of them are encapsulated.
Ps: How to Use JSONP in jQuery to obtain data across domains
The first method is to set ype to 'jsonp' In the ajax function ':
$. Ajax ({dataType: 'jsonp', url: 'http: // www.a.com/user? Id = 123 ', success: function (data) {// process data }});
The second method is to use getJSON to add callback =? Parameters:
$. GetJSON ('HTTP: // www.a.com/user? Id = 123 & callback =? ', Function (data) {// process data });
You can also simply use the getScript method:
// You can also define the foo method function foo (data) {// process data} $. getJSON ('HTTP: // www.a.com/user? Id = 123 & callback = foo ');
JSONP Application
JSONP can play a very important role in open APIs. Open APIs are used in developers' own applications, many applications are often deployed on developer servers rather than Sina Weibo servers. Therefore, cross-origin request data has become a major problem that developers need to solve, the majority of open platforms should support JSONP, which is very good for Sina Weibo open platforms (although some APIs are not described, they can actually be called using JSONP ).
Articles you may be interested in:
- AJAX cross-origin request to obtain JSON data using JSONP
- Detailed decryption of jsonp cross-origin requests
- Http cross-origin request using script: JSONP implementation principle and code
- Use of ajax jsonp for cross-origin requests
- Jsonp cross-origin request data for mobile phone number query instance analysis