Using Jsonp to implement cross-domain requests, spring MVC+JQuery

1 What is Jsonp?

JSONP (JSON with Padding) is a "usage mode" of data format JSON that allows web pages to request data from other domains.Another new way to solve this problem is to share resources across sources.

Due to the homology policy, web pages located at www.42du.cn generally cannot communicate with servers other than www.42du.cn, with the exception of the < script > element of HTML.With this open policy of the < script > element, web pages can get JSON data generated dynamically from other sources, and this usage pattern is called JSONP.The data captured with JSONP is not JSON, but any JavaScript that runs with a JavaScript interpreter rather than a JSON parser.

2 Jsonp Basic Principles

To understand how this pattern works, imagine having a URL that returns a JSON file with which a JavaScript program can request data using XMLHttpRequest.Suppose our URL is http://tools.42du.cn/jsonp/st... .Assuming that the st_no of iFat 3 is 3, when the browser passes the st_id of iFat 3 through the URL, that is, grab http://tools.42du.cn/jsonp/st... , get:

{"st_no":3,"st_name":"iFat3","st_desc":"iFat3 Is the super slag of the school"}

This JSON data may be generated dynamically based on query parameters passed from past URL s.

At this point, it is conceivable to set the src attribute of the < script > element to a URL that returns JSON, which also means it is possible to grab JSON from HTML pages through script elements.

However, a JSON file is not a JavaScript program.In order for the browser to run on the < script > element, the URL returned from the src must be a runnable JavaScript.In the usage pattern of JSONP, this URL returns the dynamically generated JSON wrapped up by a function call, which is the origin of JSONP's "padding" or "prefix".

Traditionally, browsers provide the name of a callback function as part of a named query parameter in a request to the server, for example:

 <script type="text/javascript"
    src="http://tools.42du.cn/jsonp/student/3?callback=callback>
 </script>

The server populates the callback function with JSON data before passing it to the browser.The browser's response is no longer a mere data narrative but a script.In this example, the browser gets:

/**/callback({"st_no":3,"st_name":"iFat3","st_desc":"iFat3 Is the super slag of the school"});

3 Server-side Generation Jsonp

In this example, Jsonp is generated using the JSonp processing portion of the Spring Framework, read the official documentation for more details.Links to the spring section of the relevant materials, I strongly recommend that you read the official documents before you write code in the actual development process.

3.1 Model object

The get and set methods for the Student model object are not listed.

public class Student extends BaseBean implements Serializable {
    private Integer st_no;
    private String st_name;
    private String st_desc;
}

3.2 spring Jsonp Processing

@ControllerAdvice
@RequestMapping("/jsonp")
public class StudentJsonpAdvice extends AbstractJsonpResponseBodyAdvice {
    private List<Student> students = new ArrayList<Student>();
    public StudentJsonpAdvice() {
        super("callback");
        initData();
    }
    @RequestMapping(value="/student/all",method= RequestMethod.GET)
    @ResponseBody
    public List<Student> list(){
        return students;
    }
    @RequestMapping(value="/student/{st_no}",method= RequestMethod.GET)
    @ResponseBody
    public Student info(@PathVariable Integer st_no){
        if(st_no != null) {
            if(st_no > 0 && st_no <4) {
                return students.get(st_no -1);
            }
            return students.get(0);
        }
        return null;
    }
    private void initData() {
        Student st1 = new Student(1,"Wang Meimei","Wang Mei is the school flower");
        Student st2 = new Student(2,"Mao San Fat","Mao San-fat is the school superpower");
        Student st3= new Student(3,"iFat3","iFat3 Is the super slag of the school");
        students.add(st1);
        students.add(st2);
        students.add(st3);
    }
}

4 Client gets Jsonp data

Use JQuery's ajax method to get data for all students, and use callback functions to insert data into the page.More JQuery's ajax methods are available in the JQuery section of the documentation.

function callback(data) {
        $(data).each(function(i,item){
            $("#stu_ul").append("<li>"+item.st_name+"</li>");
        });
    }
    $(document).ready(function () {
        $.ajax({
            type:"get",
            dataType:"jsonp",
            url:"http://tools.42du.cn/jsonp/student/all",
            jsonpCallback:"callback"
        });
    })

5 Relevant Data

Spring processes Jsonp documents

Official JQuery Ajax Documentation

Wikipedia Jsonp entry

Newbie Jsonp Tutorial

Introduction to JSON in Chinese

Student List Jsonp Address

Student Information Jsonp Address

Keywords: Javascript JSON Spring JQuery

Added by lightningrod66 on Tue, 25 Jun 2019 19:06:53 +0300