Project Development, a separate, can also be integrated sub-business module needs to open the relevant API interface, first, the project itself using Jersery to achieve restful webservice in the form of a noun to publish the API. The interesting thing is that in the actual operation of the colleague in the way of Ajax cross-domain request to call the API, not to mention the success or not, the way this is "funny". And he explored the irrationality of this approach, and then chose Jersey Client for remote invocation. Only he encountered problems in cross-domain requests, his leisure time to solve, this is the origin of this article.
jquery has two workarounds for cross-domain requests, each of which is the Jquery.ajax JSONP format and jquery.getscript approach to jquery, both of which support only the Get method.
The main talk here is the implementation of JSONP cross-domain.
JSON format we often use, but JSONP is not so often used, so first need to have an understanding of JSONP.
JSONP explanation
before explaining JSONP, we need to understand the concept of "homologous strategy" , which is helpful for understanding cross-domain. For security reasons, browsers exist in the same origin policy mechanism, and the same-origin policy prevents documents or scripts loaded from one source from getting or setting properties of a source-loaded document. A little bit around, the simple point is that the browser limit script can only interact with the protocol, the same domain name, the same port as the script .
JSONP is to solve this problem, JSONP is the English JSON with padding abbreviation, is an unofficial agreement. He agreed to generate the script tags return value client from the server, and use JavaScript callback to implement Web Access. Jsonp is a script tag injection that adds the response returned by the server to the page to implement a specific function.
In short, JSONP itself is not a complex thing, but the dynamic parsing of JavaScript documents through the SCIRPT tag bypasses the browser's homologous strategy.
JSONP principle and realization
Next, you will actually simulate a cross-domain request resolution. The backend is the Spring MVC architecture, and the frontend is cross-domain via Ajax.
1, first client need to register a callback (the server through the callback (JSONP) can get the JS function name (jsonpcallback)). Then in JavaScript
method to generate a function.
2, Next, the JSON data directly into the function in the way, so that the generation of a JS grammar document, returned to the client.
3. The last client browser dynamically parses the script tag and runs the returned JavaScript syntax document fragment, where the data is passed in as a reference to the pre-defined
callback function (dynamically run callback function).
Such dynamic parsing of the JS document and the Eval function are similar.
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",//server used to receive the function name of the callback call jsonpcallback: "Success_jsonpcallback",// Callback the function name, the server will pass the name and data back together success:function (JSON) { alert (json[0].name); } );
Note: JSONP will create a query string of callback=?
, the parameter is loaded after the requested URL, and the server should precede the JSON data with a callback function
name so that a JSONP request is completed. This means that the server side needs to handle the returned data in the form of the following format:
Jsonpcallback ([{name: "Jhon"}])
next look at the server side for the above code processing:
@RequestMapping ("/get") public void Get (HttpServletRequest req,httpservletresponse res) {Res.setcontenttype ("text/ Plain "); String callbackfunname =req.getparameter ("Callbackparam");//Get JS function name try {res.getwriter (). Write (Callbackfunname + "( [{name:\ "john\"}]); Returns JSONP data} catch (IOException e) {e.printstacktrace ();}}
after the front-end Ajax cross-domain request is triggered, the JSON data can be effectively obtained, such as the following:
at this point, Ajax cross-domain requests have been overcome, but there are still two points to note:
1, there is no error handling on the JSONP call, the dynamically inserted script is valid, then the call is run, the invalidation silently fails (no matter what hint).
2, Jsonp is not trusted by the use of services will have a certain security risks, untrusted services provided by the script may be malicious.
Ajax+spring MVC for cross-domain requests in jquery