有时需要跨域请求接口,这时需要返回jsonp格式的数据,示例代码如下:
后端Java代码
@RequestMapping("/jsonp") @ResponseBody public String loginjsonp(HttpServletRequest request,HttpServletResponse response,String params,String callback){ String result = "{'code':'200','data':'001','msg':'操作成功','success':'true'}";
result=callback+"("+result+")"; return result; }
前端js代码
$.ajax({ url: 'http://test.aaa.g.cn/user/jsonp.do', type: 'post', dataType:'jsonp', jsonp: "callback", data: {"params":'{"client_id":"6b896da1307f4dd08067faa8ec4843ad","username":"test06","password":"1191111","usertype":"0"}'}, success:function(data){ alert(data.code); alert(data.msg); }, error:function(data){ alert(data.code); alert(data.msg); } });