首页 > 代码库 > 利用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