后端返回值以json的格式返回,前端以json格式接收

以随便一个类为例子:这个例子是查询企业主营类别前5事项

一、以json数组的格式返回到前端中

(1)后端将结果绑定到param中,然后将结果以为json数组的格式返回到前端

/**
     * 查询企业主营类别前5事项
     * @param request
     * @param response
     * @param config
     * @throws Exception
     * @author hongxy
     * 2017年6月1日下午2:21:14
     */
    public void getEnterpriseMainCategory(HttpServletRequest request,
            HttpServletResponse response, ServletConfig config) throws Exception {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");  
        Map param = new HashMap();
        PrintWriter wirte = null; 
        //获得企业名称
        String custName = RequestUtil.getString(request, "companyName");
        //判断企业名称是否为空
        if (StringUtils.isBlank(custName)) {
            param.put("status", "400");
            param.put("desc", "企业名称为空!");
        } else {
            workService = new WorkServiceImpl();
            //查询是否存在该企业
            Map enterpriseInfo = workService.getEnterpriseInfoByCustName(custName);
            //不存在该企业
            if (enterpriseInfo == null) {
                param.put("status", "400");
                param.put("desc", "企业名称不存在!");
            } else {//存在该企业,查询企业主营类别前5事项
                //根据企业名称查询出该企业近一年的已办事项
                String approveTypeList = workService.getEnterpriseWorksInfoByCustName(custName);
                //根据行业类别查询企业名称
                String custNameListByIndustry  = workService.getEnterpriseNameByIndustry((String) enterpriseInfo.get("INDUSTRY"));
                //查询企业主营类别前5事项
                List mainProjectList = workService.getApproveInfoList(custNameListByIndustry,approveTypeList);
                param.put("status", "200");
                param.put("desc", "处理成功");
                param.put("data", mainProjectList);
            }
        }
      //声明JSONArray对象并输入JSON字符串
          JSONArray array = JSONArray.fromObject(param); 
          wirte = response.getWriter(); 
          wirte.print(array); 
    }

(2)前端先将接受到的数据转换成json格式,不然就不能获取里面的值了,因为Ajax返回的值默认是字符串类型

将接收到的值转换成json格式的核心代码:(具体的取值可以输出到前端控制台,这样方便取值)

var msg=jQuery.parseJSON(msg);
$.ajax({
       url: '${path.appMain}?service=work&func=getEnterpriseMainCategory',
       async: false,
       type: 'POST',
       data: {
           companyName:companyName
       },
       success: function(msg){
               var msg=jQuery.parseJSON(msg);
               var mainProjectList = "";
              mainProjectList +="<li>与您的“主营项目类别”相同的企业,办理最多的事项有:</li>"
              for (var i = 0; i < msg[0].data.length; i++) {
               mainProjectList += "<li><a href='javascript:void(0);'>"+
                                (i+1) + "." + msg[0].data[i].approveName +
                                "</a></li>";
            }
            $('#mainProjectList').html(mainProjectList);
        }
});

 二、以json的格式返回到前端中(常用)

(1)后端将结果绑定到data中,然后将结果以为json的格式返回到前端

     /**
     * 查询企业主营类别前5事项
     * @param request
     * @param response
     * @param config
     * @throws Exception
     * @author hongxy
     * 2017年6月1日下午2:21:14
     */
    public void getEnterpriseMainCategory(HttpServletRequest request,
            HttpServletResponse response, ServletConfig config) throws Exception {
        request.setCharacterEncoding("UTF-8");
        JSONObject json = new JSONObject();
        Map param = new HashMap();
        //获得企业名称
        String custName = RequestUtil.getString(request, "companyName");
          //判断企业名称是否为空
          if (StringUtils.isBlank(custName)) {
              json.put("status", "400");
              json.put("desc", "企业名称为空!");
          } else {
              workService = new WorkServiceImpl();
              //查询是否存在该企业
              Map enterpriseInfo = workService.getEnterpriseInfoByCustName(custName);
            //不存在该企业
            if (enterpriseInfo == null) {
                  json.put("status", "400");
                  json.put("desc", "企业名称不存在!");
            } else {//存在该企业,查询企业主营类别前5事项
                //根据企业名称查询出该企业近一年的已办事项
                String approveTypeList = workService.getEnterpriseWorksInfoByCustName(custName);
                //根据行业类别查询企业名称
                String custNameListByIndustry  = workService.getEnterpriseNameByIndustry((String) enterpriseInfo.get("INDUSTRY"));
                //查询企业主营类别前5事项
                List mainProjectList = workService.getApproveInfoList(custNameListByIndustry,approveTypeList);
                  json.put("status", "200");
                  json.put("desc", "处理成功");
                  json.put("data", mainProjectList);
            }
          }
          // 响应请求
         SysInfo.responseJsonMsg(response, json.toString());
    }

(2)前端接收json数据并在前端进行显示

$.ajax({
       url: '${path.appMain}?service=work&func=getEnterpriseMainCategory',
       async: false,
       type: 'POST',
       data: {
           companyName:companyName
       },
       success: function(msg){
               var mainProjectList = "";
            mainProjectList +="<li>与您的“主营项目类别”相同的企业,办理最多的事项有:</li>"
            if(msg.data.length == 0){
                mainProjectList += "<li>查找不到相关的事项!</li>";
            } else{
                for (var i = 0; i < msg.data.length; i++) {
                    mainProjectList += "<li><a href='javascript:void(0);'>"+
                                (i+1) + "." + msg.data[i].approveName +
                                "</a></li>";
                }    
            }
            $('#mainProjectList').html(mainProjectList);
        }
     });
原文地址:https://www.cnblogs.com/xuegu/p/6951668.html