Spring 跨域请求
1.Jsp的跨域请求
后台jsp代码:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% String callback = request.getParameter("callback"); out.print(callback+"([{name:'jsonp',age:'30'},{name:'jack',age:'90'}]);"); out.print(callback); %>
前端代码1:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% String callback = request.getParameter("callback"); out.print(callback+"([{name:'jsonp',age:'30'},{name:'jack',age:'90'}]);"); out.print(callback); %>
前端代码2:
<script type="text/javascript"> $.getJSON("http://localhost:8080/Jsonp/jsonp.jsp?callback=?", function(json){ alert(json[0].name); }); </script>
2.Spring 的跨域请求
下面给出一个Controller的例子;
/** * 获取单位信息列表json
* 注意这里把@ResponseBody 去掉了 */ @RequiresPermissions("sys:unitnew:view") @RequestMapping(value = "jsonp") public void getListaa(HttpServletRequest request,HttpServletResponse response, Model model, @RequestParam(value = "pageNumber", defaultValue = PAGE_NO) int pageNumber, @RequestParam(value = "pageSize", defaultValue = PAGE_SIZE) int pageSize) { try { PageHelper.startPage(pageNumber, pageSize, true); Map<String, Object> params = builderParams(request, model); params.put("queryCondition", " AND deleted != 1 "); List<AssistantUnit> result = manger.findByParams(params); System.out.println("获取单位信息json:result:" + result.size()); PageUtils<AssistantUnit> page = new PageUtils<AssistantUnit>(result); String aaa = JsonUtil.pojo2json(page);// 这个是把序列化 String callback = request.getParameter("callback"); //response.getWriter().print(callback+"([{name:'jsonp',age:'30'},{name:'jack',age:'90'}]);"); response.getWriter().print(callback+"(["+aaa+"]);"); response.getWriter().print(callback); } catch (Exception e) { logger.warn("获取单位信息信息异常:", e); } }
前端调用:
下面是调用的地方:
这个在Load里面: addScriptTag('http://192.168.1.103:8080/aaaaa-web/unit/jsonp?callback=dosomething');
function addScriptTag(src) { var script = document.createElement('script'); script.setAttribute("type","text/javascript"); script.src = src; document.body.appendChild(script); } function dosomething(data) { console.log(data[0].endRow); console.log('Your public IP address is: bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'); console.log('Your public IP address is: bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'); };
顶
收藏
关注
评论
作者:王思明
出处:http://www.cnblogs.com/maanshancss/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。所有源码遵循Apache协议,使用必须添加 from maanshancss
出处:http://www.cnblogs.com/maanshancss/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。所有源码遵循Apache协议,使用必须添加 from maanshancss