Learn more about Jsonp troubleshooting cross-domain access

Source: Internet
Author: User
Tags script tag

in this project, we do the full use of JSONP which is a feature of cross-border, complete simple single sign-on authentication and authority control unification. Tao, each has each merit, each has each merit, chooses what way realizes completely depends on our own or the project manager's development experience, the understanding degree to the various frameworks often determines the current development project the overall structure.

This is not a new thing that has been created in a vacuum. However, a feature of JS is not mentioned before we did not notice that the original JS can also be used to cross the domain, feel that we have learned to understand the things are not enough depth, some superficial, JS most in the browser to perform a variety of dynamic effects, Developers who develop JS should start with the features of the browser in mind. In order to not be restricted by the browser to give JS this sacred duty, browser restrictions is a security policy inside a policy, called the same-origin policy.

Homologous policy

The same origin means that the protocol, domain name, port are the same, only have a not the same is not the same origin of the access address. One page of a browser is not able to obtain data from an address that is not from the same origin, and when each page is loaded, the browser proactively infers whether the data obtained from a source address. Assume that you are not blocked by the browser.

Like the security of the Conference, just agree to a certain type of people with a pass, others will not let into the outside, and JS has a feature to cross the security through the special way into the non-blocking.

Resolve the same-origin policy issue Jsonp
JSONP (JSON with Padding) is a "usage pattern" of data format JSON that allows Web pages to retrieve data from other domains.

The reason why it is called JSONP can be understood as the main function and purpose is to obtain JSON format data from other domains, which is its main application, the other functions are not practical.

Principle

The principle is also very easy to understand, it is able to cross-domain is the use of the script tag cross-domain capabilities. Imagine? Have you ever thought of a common JS file that is often introduced. How does it load into a page why does its SRC attribute write an address to load the JS file elsewhere on the page? This src attribute can be tested to fill in an arbitrarily valid address. Even files that are not in the same project folder structure are also available.

such as this link;

<span style= "FONT-SIZE:14PX;" ><script type= "Text/javascript" src= "_js/jquery-2.0.0.min.js" ></script></span>

It is simply a reference, loaded into the file when there are very many such function functions () {} ......, the same JSONP is a pattern. It also returns the JS function with the above link no difference. Just a function called a callback function needs to be predefined, and inside the function is the JSON data that is returned. Let's look at an example:

<span style= "FONT-SIZE:14PX;" ><script type= "Text/javascript" >function Getjson (JSON) {alert ("Get json= by src attribute" +json.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 that I wrote myself. Its SRC address is also a login interface address for the Application1 app deployed in Tomcat. And the above call is in a tomcat in the Application2 JSP page, belong to a different source call, and then look at the Application1 interface class

<span style= "FONT-SIZE:14PX;" > Public    actionforward logininterface (actionmapping mapping, actionform form,            httpservletrequest request, HttpServletResponse response)    {    /** infer if login succeeded */boolean IsLogin = false;//get username and    password from URL String name=request.getparameter ("name");    String Pwd=request.getparameter ("pwd"); try {//callback function name string callbackfunname = Request.getparameter ("callback");// JSON data wrapped with JSONP string, Callbackfunname + "({\" result\ ": \" "+ name +" \ "})"; SYSTEM.OUT.PRINTLN (data);//Return to interface print (data,request,response);} catch (Exception e) {e.printstacktrace ();} return null;    } </span>

The returned result is Gejson ({"Result": "Lilongsheng"}), which returns a JS code that will run the Getjson function on its own initiative. The contents of the curly braces {} are passed to this function as a number of parameters, and are called across domains.

It can be seen from above that JSON data can be obtained from a script tag in a place that has no origin.

Let's take a look at how jquery is used, just adding a single parameter to the method, and feeling a lot simpler, because the framework already encapsulates some of the details of the call relationship. As long as we set the parameters it supports cross-domain access and calls such as the following:

<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 and other frameworks such as EXT support this feature, they are based on the JavaScript base Class library encapsulated, so all have JS features.

About the application of Jsonp has recorded a episode of video, the following is

Jsonp Video Demo: Http://pan.baidu.com/s/1dDIjnTR







Copyright notice: This article blog original article. Blogs, without consent, may not be reproduced.

Learn more about Jsonp troubleshooting cross-domain access

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.