使用jsonp解决ajax跨域问题时返回json数据
使用jsonp解决ajax跨域问题时返回json数据
解决方法:
1.前端代码
$.ajax({
type: "POST",
url: "/com/start.do",
data:{bill_id:bill_id},
dataType:"jsonp",
success: function(data){
alert("返回json");
}
});
2.后台代码:
@RequestMapping("/startFlow")
public void startFlow(HttpServletRequest request,HttpServletResponse response) throws Exception{
String bill_id = request.getParameter("bill_id");
Map<Object, Object> context = service.startFlow(bill_id);
String callback=request.getParameter("callback");
if(!StringUtil.isEmpty(callback)){
response.setContentType("application/json;charset=UTF-8");
try {
//设置页面不缓存
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setCharacterEncoding("UTF-8");
PrintWriter out= null;
out = response.getWriter();
out.print(callback+"("+JSONUtil.toJSONString(context)+")");
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}