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');
};