解决方式一、
js代码
$(document).ready(function(){ var url='http://localhost:8080/WorkGroupManagment/open/getGroupById" +"?id=1&callback=?'; $.ajax({ url:url,dataType:'jsonp',processData: false,type:'get',success:function(data){ alert(data.name); },error:function(XMLHttpRequest,textStatus,errorThrown) { alert(XMLHttpRequest.status); alert(XMLHttpRequest.readyState); alert(textStatus); }}); });
后台java代码:
@RequestMapping(value = "/getGroupById") public String getGroupById(@RequestParam("id") Long id,HttpServletRequest request,HttpServletResponse response) throws IOException { String callback = request.getParameter("callback"); ReturnObject result = null; Group group = null; try { group = groupService.getGroupById(id); result = new ReturnObject(group,"获取成功",Constants.RESULT_SUCCESS); } catch (BusinessException e) { e.printStackTrace(); result = new ReturnObject(group,"获取失败",Constants.RESULT_Failed); } String json = JsonConverter.bean2Json(result); response.setContentType("text/html"); response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); out.print(callback + "(" + json + ")"); return null; }
解决方式二、
使用jsonp
var url="http://localhost:8080/WorkGroupManagment/open/getGroupById" +"?id=1&callback=?"; $.jsonp({ "url": url,"success": function(data) { alert(data.result.name); },"error": function(d,msg) { alert("Could not find user "+msg); }});