首页 > 代码库 > 利用jQuery获取jsonp
利用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=http://www.mamicode.com/=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 = "http://www.mamicode.com/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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。