ajax+spring MVC in jquery for cross-domain requests

Source: Internet
Author: User
Tags script tag

in the development of a project, a sub-business module that can be independent and can be integrated needs to open the relevant API interface, first of all, the project itself uses Jersery to implement restful webservice to publish APIs in noun form. Interestingly, in the actual operation of the colleague but through the way Ajax cross-domain request to call the API, not to mention the success or not, this is "funny", and he discussed the irrationality of this approach, and then choose Jersey Client Way to make remote calls. However, he encountered problems in cross-domain requests, his leisure time to solve, this is the origin of this article.

jquery has two solutions for cross-domain requests, namely the Jquery.ajax JSONP format and jquery.getscript mode of jquery, and both methods support the Get method only. The main talk here is the implementation of JSONP cross-domain.

JSON format we often use, but JSONP is not so common, 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 another source load document. A little bit around, the simple point is that the browser limit script can only be used with the protocol, the same domain name, the same port of the script to interact .

JSONP is to solve this problem, JSONP is the English JSON with padding abbreviation, is an unofficial agreement. He allows the server to generate a script tags return value client, through JavaScript callback to achieve site access. JSONP is an injection of a script tag 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, the solution to actually simulate a cross-domain request. The backend is the Spring MVC architecture, and the frontend is accessed across the domain through Ajax.

1, first the client needs to register a callback (the service side through the callback (JSONP) can get the JS function name (jsonpcallback)), and then in JavaScript language

method to generate a function.

2, Next, the JSON data directly into the parameter in the way, put into the function, so that the generation of a JS grammar document, returned to the client.

3. Finally, the client browser dynamically parses the script tag and executes the returned JavaScript syntax document fragment, where the data is passed as a parameter to the pre-defined

callback function (Dynamic execution callback function).

This dynamic parsing JS document is similar to the Eval function.

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 server is used to receive parameters for callback called function name                      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 parameter callback=?, this parameter will load the requested URL, the server should precede the JSON data with a callback function

name to complete a JSONP request. 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 handling of the above code:

        @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 as follows:

At this point, the Ajax cross-domain request has been resolved, but there are two points to note:

1, there is no error handling on the JSONP call, the dynamically inserted script is valid, then the execution of the call, invalid silently failed (no hint).

2, Jsonp is not trusted by the use of services will have a certain security risks, untrusted services provided by the script is malicious.



ajax+spring MVC in jquery for cross-domain requests

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.