"AngularJs"---jsonp cross-domain Access data transfer

Source: Internet
Author: User
Tags script tag domain server

People will naturally think of only one letter of the difference of the JSON bar ~

JSON (JavaScript Object Notation) and Jsonp (JSON with Padding) have only a single letter difference, but they're not the same thing at all.

JSON is a data interchange format, and Jsonp is an unofficial cross-domain data interaction protocol that relies on the ingenuity of developers. We use the latest spy war film to make an analogy, JSON is used by the underground to write and exchange information "code", and Jsonp is the message written with the signal to his comrades using the connection method. Did you see that? One is the format of describing information, and the other is the method agreed by both parties to the information delivery.

The browser is a mechanism of the same origin policy, and at the global level prohibits the page from loading or executing any script from a domain different from its source.

Jsonp is a way to request data from different domains by bypassing the security restrictions of the browser.

When invoking a JS file on a Web page, it is not affected by cross-domain (not only that, we also find that all tags that have the attribute "src" have cross-domain capabilities, such as <script>, , <iframe>);

If you want to access data across domains by using a pure Web side (ActiveX controls, service-side proxies, websocket of the future HTML5, and so on), there is only one possibility of trying to load data into a JS-formatted file on a remote server for client invocation and further processing JSON, the pure character data format can be concise description of complex data, by JS native support, so in the Web client by the same way as the call script to invoke the cross-domain server dynamically generated JS format file (generally with JSON suffix), it is obvious that The purpose of the server is to dynamically generate JSON files in order to load the data required by the client. in order to facilitate the use of data by the client, gradually formed an informal transport protocol, people call it Jsonp, one of the main points of the protocol is to allow users to pass a callback parameter to the server, The callback parameter is then used as the function name to wrap the JSON data when the server returns data, so that the client can customize its own function to automatically process the returned data.

The principle of JSONP is to use the <script> tag to initiate a GET request to replace the XHR request. JSONP generates a <script> tag and plugs into the DOM, and the browser takes over and sends the request to the address pointed to by the SRC attribute.

When the server returns a request, the response result is wrapped into a JavaScript function that is called by the callback function that corresponds to the request.

ANGULARJS provides a JSONP helper function in the $http service. The Jsonp method of the $http service can send the request as follows:

$http. JSONP ("Https://api.github.com?callback=JSON_CALLBACK"). Success (function (data) {

Data
});

When the request is sent, Angularjs generates a <script> tag in the DOM as follows:

<script src= "Https://api.github.com?callback=angular.callbacks._0" type= "Text/javascript" ></script>

Note that Json_callback was replaced with a custom function that was specifically generated for this request. When the server that supports JSOPN returns data, the data is wrapped in a named function generated by Angularjs angular.callbacks._0 in this example, the GitHub server returns the JSON data contained in the callback function, which looks like this:

Shorthand

Angular.callbacks._0 ({

' Meta ': {
' X-ratelimit-limit ': ' 60 ',
' Status ': 200
},
' Data ': {
' Current_user_url ': ' Https://api.github.com/user '
}
})
When Angularjs invokes the specified callback function, the $http promise object is resolve. When we develop our own back-end services that support JSONP, make sure that the response data is included in the callback function specified by the request. The use of JSONP requires awareness of potential security risks. First, the server is completely open, allowing the backend service to invoke any JavaScript in the app. External sites (or deliberate attackers) that are not under our control can change the script at any time, making our entire site vulnerable. It is possible for the server or middleman to return additional JavaScript logic to the page, exposing the user's privacy data. Because the request was sent by the <script> tag, only the GET request can be sent through JSONP. And the exception to the script is difficult to handle. Use JSONP be careful and communicate only with servers that you trust and can control.

One sentence is to use the script tag to bypass the same-origin policy, get a similar data, Jsonpcallback is the page exists callback method, parameter is the JSON to get.

The use of JSONP in jquery

Myurl = "Http://localhost:8090/api/test"; $.ajax ({type: "GET", Url:myurl, DataType: "Jsonp", Jsonp: "Callback", jsonpcal Lback: "Jsonpcallback", success:function (data) {alert (data.msg);
}}); function Jsonpcallback (data) {alert (data);}
1.jsonp can only use GET requests to solve the same-origin problem, return JavaScript code, because the request JavaScript file is not the same origin problem. 2. When the request data type is JSONP, the Callback=jsonpcallback is added to the URL, http://localhost:8090/api/testcallback=jsonpCallback3. The Jsonpcallback function is defined in the foreground JavaScript, and this function must be defined under window, which is the global function, otherwise it cannot be found. 4. The background gets the callback parameter value of the request Jsonpcallback, which returns the string "Jsonpcallback (Result)", and result is returned. 5. The request returns a script tag that calls the Jsonpcallback function first, and the success function is called, regardless of whether the function is found. 6. If you do not define JSONP and JSONPCALLBACK,JSONP default to "callback", Jsonpcallback will be the function name that jquery automatically generates.

Use of JSONP in Angularjs

Myurl = "Http://localhost:8090/api/testcallback=JSON_CALLBACK"; $http. Jsonp (Myurl). Success (
function (data) {alert (data); }); 1.angularJS uses the $HTTP.JSONP function 2. Specify the callback and callback function names, the success callback function is called when the function name is Json_callback, and the json_callback must be all uppercase. 3. You can also specify a different callback function, but it must be a global function defined under window. Callback5 must be added in 4.url. When callback is Json_callback, only success is called, even if there is a Json_callback function in the window, the function is not called.

"AngularJs"---jsonp cross-domain Access data transfer

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.