利用jQuery获取jsonp
前端js代码:
$.ajax({ url: ‘http://localhost:8080/webApp/somejsonp‘, dataType: "jsonp", jsonp: "callback", success: function (data) { console.log(data) } })
服务端代码:
本例采用java实现 使用的springmvc伪代码
private boolean ifJsonp(HttpServletRequest request,HttpServletResponse response,Map<String, Object> map) throws Exception{ // jsonp String callback = request.getParameter("callback"); if(StringUtils.isNotBlank(callback)){ callback = callback.trim(); request.setAttribute("data", map); request.setAttribute("callback", callback); request.getRequestDispatcher("/jsonpData").forward(request, response); return true; } return false; }
@RequestMapping("/jsonpData") public @ResponseBody String genJasonData(HttpServletRequest request,HttpServletResponse response){ Object data = request.getAttribute("data"); String callback = (String) request.getAttribute("callback"); if(data==null||StringUtils.isBlank(callback)){ return "{\"result\":\"-1\",\"message\":\"未知错误\"}"; } try { response.setContentType("application/x-javascript;charset=UTF-8"); response.setCharacterEncoding("UTF-8"); response.getOutputStream().write((callback+"(").getBytes()); JsonGenerator generator = this.objectMapper.getJsonFactory().createJsonGenerator(response.getOutputStream(), JsonEncoding.UTF8); this.objectMapper.writeValue(generator, data); response.getOutputStream().write((")").getBytes()); } catch (Exception e) { return "{\"result\":\"-1\",\"message\":\"未知错误\"}"; } return null; }
服务端使用:
@RequestMapping(value = "/somejsonp") public Map<String, Object> findRcbChannelTabsInRecordID(HttpServletRequest request,HttpServletResponse response) throws Exception{ List list = new ArrayList(); Map<String, Object> map = new HashMap<String, Object>();try { list = service.queryData(map);//要查询的数据 } catch (Throwable t) { } map.put("Data", list);// jsonp if(ifJsonp(request, response, map)){ return null; } return map; }
来源更多请参考:http://www.cnblogs.com/lemontea/archive/2012/12/11/2812268.html
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。