Implement cross-origin requests using Ajax + Spring MVC in jQuery
In project development, an independent or integrated sub-business module needs to open APIs externally. First, the project itself uses jersery to implement RESTful webservice to publish APIs in the form of nouns. Interestingly, in actual operations, my colleagues call this API through Ajax cross-origin requests, not to mention whether the API is successful or not. This method is "funny, he discussed with him the irrationality of this approach, and then selected jersey client for remote calls. However, he encountered a problem in cross-origin requests and solved it in his spare time. This is the origin of this article.
JQuery has two solutions for cross-origin requests: jQuery's jquery. ajax jsonp format and jquery. getScript method. Both methods only support the get method. Here we mainly discuss the implementation of jsonp cross-origin.
Json format is often used, but jsonp is not so commonly used. Therefore, you must first understand jsonp.
JSONP description
Before explaining JSONP, we need to understand the concept of "same-origin policy", which is helpful for understanding cross-origin. For security reasons, the browser has a same-origin policy mechanism. The same-origin policy prevents you from retrieving or setting attributes of a document or script loaded from one source. A bit around, simply put, the browser restricts that scripts can only interact with scripts of the same Protocol, same domain name, and same port.
JSONP is used to solve this problem. JSONP is short for JSON with Padding and is an unofficial protocol. It allows the server to generate the script tags return value client and implement site access in the form of javascript callback. JSONP is a script tag injection. Adding the response returned by the server to the page is a specific function.
In short, JSONP itself is not a complex thing, that is, the dynamic parsing of javascript documents through the scirpt tag bypasses the browser's same-source policy.
JSONP Principle and Implementation
Next, we will simulate a solution for cross-origin requests. The backend is in the Spring MVC Architecture, and the front end uses Ajax for cross-origin access.
1. First, the client needs to register a callback (the server can get the js function name (jsonpCallback) through this callback (jsonp), and then use JavaScript
Method to generate a function
2. Next, place the JSON data directly in the function as an input parameter. In this way, a js syntax document is generated and returned to the client.
3. Finally, the client browser dynamically parses the script tag and executes the returned JavaScript syntax file segment. At this time, the data is passed as a parameter to the pre-defined
Callback function ).
This kind of dynamic parsing js documentation is similar to eval functions.
The next step is how to implement the client code.
$. Ajax ({type: "get", async: false, url: "http: // localhost: 8080/buy/get", dataType: "jsonp", jsonp: "callbackparam", // The parameter jsonpCallback of the function name used by the server to receive callback calls: "success_jsonpCallback", // The Name Of The callback function. The server will pass the name and data back together to success: function (json) {alert (json [0]. name );}});
Note: jsonp creates a query string parameter callback = ?, This parameter loads the request URL. The server should add a callback function before the JSON data.
To complete a JSONP request. That is to say, the server needs to process the returned data in the following format:
jsonpCallback([{ name:"jhon"}])
Next, let's take a look at how the server handles the above Code:
@ RequestMapping ("/get") public void get (HttpServletRequest req, HttpServletResponse res) {res. setContentType ("text/plain"); String callbackFunName = req. getParameter ("callbackparam"); // obtain the js function name try {res. getWriter (). write (callbackFunName + "([{name: \" John \ "}])"); // return jsonp data} catch (IOException e) {e. printStackTrace ();}}
After the front-end Ajax cross-origin request is triggered, JSON data can be effectively obtained, as shown in the following figure:
So far, Ajax cross-origin requests have been resolved, but there are two points to note:
1. There is no error handling for JSONP calls. If the dynamically inserted script is valid, the call is executed. If the JSONP call is invalid, it will silently fail (without any prompt ).
2. The use of untrusted JSONP services may pose security risks. scripts provided by untrusted services may be malicious.