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

  • 相关阅读:
    P2569 [SCOI2010]股票交易 dp 单调队列优化
    luogu P4516 [JSOI2018]潜入行动
    7.12 NOI模拟赛 积性函数求和 数论基础变换 莫比乌斯反演
    luogu P2607 [ZJOI2008]骑士 tarjan dp
    7.11 NOI模拟赛 graph 生成函数 dp 多项式
    luogu P1973 [NOI2011]NOI 嘉年华 dp
    HTML-01文档
    修改服务器为Root直接登录
    strust2--postman遇到的ognl问题
    python-13-函数
  • 原文地址:https://www.cnblogs.com/cxyj/p/3884934.html
Copyright © 2020-2023  润新知