In-depth understanding of jsonp for cross-origin access and in-depth understanding of jsonp for cross-origin access

Source: Internet
Author: User

In-depth understanding of jsonp for cross-origin access and in-depth understanding of jsonp for cross-origin access

In our project, we fully utilize the jsonp cross-domain feature to complete simple single sign-on function and unified permission authentication control, the implementation idea is not complex. Compared with various products that implement Single Sign-on, it can be said that each has its own advantages and its own advantages. The method of implementation depends entirely on the development experience of ourselves or the project manager, the understanding of various frameworks often determines the overall architecture of the current development project.

This is not a new thing created out of thin air. It is just a feature of JS. We haven't mentioned it before, and we haven't noticed that js that is often used in the past can still be used across domains, it seems that we have not fully understood what we have learned. JS is mostly running in browsers to achieve various dynamic effects, the developer of js should have taken into account the features of the browser at the beginning. In order not to be restricted by the browser, JavaScript has been given this sacred responsibility. browser restrictions are a policy in the security policy, the same-origin policy.

Same-origin policy

The same source means that the Protocol, domain name, and port are all the same. If there is a different one, the access address is different from the source. A browser cannot retrieve data from a different source address on a page, when a page is loaded, the browser automatically determines whether the obtained data comes from a source address. If not, the browser will block the data.

Like the security check of a meeting, only a certain type of people with passes are allowed to access the meeting, while others are not allowed to access the outside, js has a feature that can pass security checks and access through special channels is not blocked.

Solve the same-source policy problem jsonp
Jsonp (JSON with Padding) is a "usage mode" in json format that allows webpages to obtain information from other domains.

The reason why jsonp can be understood as the main function and purpose is to obtain json-format data from other domains. This is its main application, and other functions are not used for the moment.

Principle

The principle is also easy to understand. The reason why it can cross-origin is to use the cross-origin capability of script tags. Imagine? Have you ever thought about a common js file that is often introduced, how is it loaded to the page? Why can I load js files elsewhere to the page by writing the src attribute to an address, after testing, this src attribute can be filled with any valid address, even if the file is not in the same project directory structure.

For example, this link;

<span style="font-size:14px;"><script type="text/javascript" src="_js/jquery-2.0.0.min.js"></script></span>

It is just a reference. Many such functions (){}.................., Similarly, jsonp is such a mode. It also returns the js function. There is no difference between the above link, but the function name is called the callback function, which needs to be defined in advance. The function contains the returned json data. Let's look at an example:

<Span style = "font-size: 14px;"> <script type = "text/javascript"> function getjson (json) {alert ("Get json =" + json through the src attribute. result) ;}</script> <script type = "text/javascript" src = "http: // localhost: 28080/application1/login. do? Method = loginInterface & callback = getjson & name = lilongsheng "> </script> </span>

This is a js Tag I wrote myself. Its src address is the login interface address of the application1 application deployed in another tomcat, and the above call is on the application2 jsp page of another tomcat, it is a non-same-origin call. Let's take a look at the interface class in application1.

<Span style = "font-size: 14px;"> public ActionForward loginInterface (ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {/** determine whether the logon is successful */boolean isLogin = false; // obtain the username and password String name = request from the URL. getParameter ("name"); String pwd = request. getParameter ("pwd"); try {// callback function name String callbackFunName = request. getParameter ("callback"); // use json data packaged by jsonp String data = callbackFunName + "({\" result \ ": \" "+ name + "\"}) "; System. out. println (data); // return to the print (data, request, response);} catch (Exception e) {e. printStackTrace () ;}return null ;}</span>

The returned result is gejson ({"result": "lilongsheng"}), and a JS Code is returned. It will automatically execute the getjson function, the content in braces {} is passed to this function as a parameter to complete cross-origin calls.

From the above, we can see that the script tag can obtain json data from different sources.

Let's take a look at how jquery is used. Just adding a parameter to the method can be implemented. It feels much simpler, because the framework has encapsulated some detailed call relationships for us, as long as the parameter is set, cross-origin access is supported. The call is as follows:

<Span style = "font-size: 14px;"> function getJsonp () {var name = $ ("# name "). val (); var pwd = $ ("# pwd "). val (); $. ajax ({url: "http: // localhost: 28080/application1/login. do? Method = loginInterface & name = "+ name +" & pwd = "+ pwd, type:" post ", dataType:" jsonp ", jsonp: 'callback', success: function (data) {alert (data. result) ;}, error: function () {alert ("network connection failed! ") ;}}) ;}</Span>

In addition to jquery, ext and other frameworks support this feature. They are encapsulated based on the javaScript base class library, so they all have the characteristics of js.

How to Apply jsonp has recorded a set of videos. below is

Jsonp video demo: http://pan.baidu.com/s/1dDIjnTR








Does the jsonp data returned from cross-origin need to be provided to the callback function?

The backend only needs to return a string of Data copied by this function name (json name). The reason why the domain name json is a kind of data name seems to be a bit understandable, json is a type of data name. It does not support cross-domain data. The p of jsonp indicates filling, which means filling a function in front of json data and executing it using the script tag, in order to achieve the effect of cross-origin is not beautiful, is that true? Cross-origin means that you are not allowed to obtain the data name is not affected, of course, the misappropriation will define the jsonxxx function jsonp because the js script is loaded without cross-origin, so you do not need to use ajax to use a script tag through the process his src visit the ghost website background This src will add a jsonp = jsonpxxx parameters to identify the misappropriation of function name

Cross-origin access in JS

Js cannot be cross-origin. Think about other solutions.

It is best to dynamically generate the content of B to application A, so that there is no cross-origin access problem.

Or do something like system interaction,
After B is loaded, it sends A command to system A, and application A scans the front-end to see if any new command has arrived.
However, this is quite troublesome.

Related Article

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.