注:只能用get请求
前端:
$.ajax({ type: "get", async: false, url: "https://www.***.com/to/getBankRankingDate", dataType: "jsonp", jsonp: "theFunction", //指定参数名称 /* jsonpCallback: "showData", */ success: function (data) { alert(data.msg) }, error: function () { } }); |
后端:
@RequestMapping(value = "getBankRankingDate", method = RequestMethod.GET) public void getBankRankingDate(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); //所有都可访问 response.setHeader("Access-Control-Allow-Origin", "*");JSONObject json = new JSONObject(); json.put("msg", success); //前端传过来的回调函数名称 String callback = request.getParameter("theFunction"); //用回调函数名称包裹返回数据,这样,返回数据就作为回调函数的参数传回去了 String result = callback + "(" + json.toJSONString() + ")"; response.getWriter().write(result); } |