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.
Ajax side:
?
| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 |
<!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://127.0.0.1:8080/DevInfoWeb/get‘, 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://127.0.0.1:8080/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>
|
Springmvc End:
?
| 123456789101112131415161718192021 |
@RequestMapping("/get") public void get(HttpServletRequest req,HttpServletResponse res) { res.setContentType("text/plain"); String callbackFunName =req.getParameter("callbackparam");//得到js函数名称 try { res.getWriter().write(callbackFunName + "([ { name:\"John\"}])"); //返回jsonp数据 } catch (IOException e) { e.printStackTrace(); } } @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); } |
Ajax+spring MVC implements cross-domain requests (JSONP) JSONP cross-domain