ajax+spring MVC for cross-domain requests (JSONP)

Source: Internet
Author: User
Tags script tag

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.


After some efforts, the solution is as follows:

Modify the Host File

127.0.0.1 www.lbj.com

127.0.0.1 www.lbj1.com

@RequestMapping ( "/getJsonp"   @ResponseBody   public JSONPObject getJsonp(String callbackparam){  Company company= new Company();  company.setAddress( "宝驾(北京)信息技术有限公司" );  company.setEmail( "[email protected]" );  company.setName( "宝驾(上海)信息技术邮箱公司" );  company .setPhone( "12345678912" );     return new JSONPObject(callbackparam, company);     }


<!DOCTYPE html>  <meta charset= "utf-8"      <script src= "http://code.jquery.com/jquery-2.1.3.min.js" ></script>  <script>  $(document).ready(function(){              $( "#but1" ).click(function(){        $.ajax({           url: ‘http://www.lbj1.com:8082/oms/tradeIllegal/test.do‘          type:  "get"          async:  false          dataType:  "jsonp"          jsonp:  "callbackparam" //服务端用于接收callback调用的function名的参数            jsonpCallback:  "success_jsonpCallback" //callback的function名称,服务端会把名称和data一起传递回来            success: function(json) {            alert(json);           },           error: function(){alert( ‘Error‘ );}  });  });      $( "#but2" ).click(function(){        $.ajax({           url: ‘http://www.lbj.com:8082/DevInfoWeb/getJsonp‘          type:  "get"          async:  false          dataType:  "jsonp"          jsonp:  "callbackparam" //服务端用于接收callback调用的function名的参数            jsonpCallback:  "success_jsonpCallback" //callback的function名称,服务端会把名称和data一起传递回来            success: function(json) {            alert(json);           },           error: function(){alert( ‘Error‘ );}  });  });      });  </script>  <body>    <div id= "div1" > <button id= "but1" >按钮 1 </button> <br/>  <button id= "but2" >按钮 2 </button>     </body> 


ajax+spring MVC for cross-domain requests (JSONP)

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.