jsonp实现ajax跨域
前端
dataType为jsonp,若不指定回调函数名则默认为callback
$.ajax({ url:headUrl+'/img/getImgList', type:'GET', dataType:'jsonp', data:{ pageSize:5, }, success:function (data) { }, error:function () { } });
后端
参数中加入callback,这里tranresult为查询返回的对象,转换为json格式,返回 拼接成js能识别的callback方法的字符串
@RequestMapping(value = "/img/getImgList",method = RequestMethod.GET) public String getNewsList(@RequestParam(value = "currentPage", defaultValue = "1", required = false) Integer currentPage, @RequestParam(value = "pageSize", defaultValue = "5", required = false) Integer pageSize, @RequestParam(value = "callback") String callback){ TransResult transResult = new TransResult(); PageResponseDTO pageResponseDTO = new PageResponseDTO(imgService.getImgList(currentPage,pageSize)); transResult.success(); transResult.setContent(pageResponseDTO);
String data= JSON.toJSONString(transResult); return callback+"("+ data +")"; }