首页 > 网站 > WEB开发 > 正文

利用jQuery获取jsonp

2024-04-27 14:20:50
字体:
来源:转载
供稿:网友

利用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


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表