前台返回json数据的常用方式+常用的AJAX请求后台数据方式

我个人开发常用的如下所示:

之所以像下面这样下,一是前台Ajax,二是为安卓提供接口数据

现在常用的是返回JSON数据,XML的时代一去不复返

JSON相对于XML要轻量级的多

对JSON不是十分熟悉的可参考此网站:http://www.w3school.com.cn/json/index.asp

对Ajax不是十分熟悉的可参考此网站:http://www.w3school.com.cn/ajax/index.asp

 

下面例子环境为:JDK8+tomcat7+MAVEN+WINDOWS环境

框架环境为:Spring+Mybatis+SpringMVC

 

第一种方式:

@RequestMapping(value = "/getUserInfo2", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    @ResponseBody
    public String getUserInfo(String User_No, Model model) {

        User user = userService.findUserInfo(User_No);

        if (user != null) {

            Map<String, User> map = new HashMap<String, User>();

            map.put("user", user);

            model.addAttribute("user", user);

            return JSON.toJSONString(map);

        } else {

            String msg = "{\"returnMsg\":\"不存在\"}";

            Map<String, Object> returnMsg = JSON.parseObject(msg);

            return JSON.toJSONString(returnMsg);
        }

    }
    

 

第二种方式:

    @RequestMapping(value="getHeadHotelIdInfo",method=RequestMethod.POST,produces="application/json;charset=utf-8")
    @ResponseBody
    public String getHeadHotelIdInfo(HttpServletRequest request) {
                
        String ids = request.getParameter("id");
        
        Integer id = new Integer(ids);
        
        Map<String,Object> map = new HashMap<String,Object>();
        
        HeadHotel hh = headHotelService.selectById(id);
        
        map.put("hh", hh);
        
        return JSONObject.toJSONString(map);
        
        
        
    }

 

第三种方式:

    @RequestMapping(value="/deleteHeadHotelInfo", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    @ResponseBody
    public Object deleteHeadHotelInfo(HttpServletRequest request) {
            
        JSONObject json = new JSONObject();
        String ids = request.getParameter("id");
        logger.info(ids);
        Integer id = new Integer(ids);
        HeadHotel hh = headHotelService.selectById(id);
        
        try {
            
            int lines = hotelChainService.TreeSelectHotelChainSize(hh.getNo());
            
            if(lines==0) {
                headHotelService.deleteHeadHotelInfo(id);
        
            
                json.put("returnCode", "000000");
                json.put("returnMsg", "删除集团公司成功");
                logger.info("删除成功");
                
            }else {
                
                
                json.put("returnCode", "000000");
                json.put("returnMsg", "存在子酒店不能删除");
                logger.info("删除失败");
                
            }
            
            
            
        } catch (Exception e) {
            e.printStackTrace();
       
            json.put("returnCode", "111111");
            json.put("returnMsg", "删除集团公司失败");
            logger.error("删除失败");

        }
        return json;
    }

 

第四种方式:

	@RequestMapping(value="removePermission",method=RequestMethod.POST,produces="application/json;charset=utf-8")
	@ResponseBody
	public Object removePermission(@RequestBody QueryVo qv,HttpServletRequest request, Model model) {
		JSONObject json = new JSONObject();
	
		Integer id[] = qv.getId();
		
		int size=java.lang.reflect.Array.getLength(qv.getId());
		logger.info("ID数量:"+size);  
		try {
			for (int i = 0; i < id.length; i++) {
				RoleResource rr = new RoleResource();
				rr.setId(id[i]);
				logger.info("ID:"+id[i]);
				List<RoleResource> rs = new ArrayList<RoleResource>();
				rs.add(rr);
				roleResourceService.removeRoleResourceStatus(rs);
			
			}
			
			json.put("returnCode", "000000");
			json.put("returnMsg", "权限修改成功");
			logger.info("权限修改成功");
			
		} catch (Exception e) {
			json.put("returnCode", "000000");
			json.put("returnMsg", "权限修改失败");
			logger.error("权限修改失败");
			
		}

		return json;
		
	   

	}
	

 

结合QueryVO:

package cn.pms.vo;

import java.util.List;

import cn.pms.model.AccountCoupon;
/**
 * 多参数传递定义QueryVo
 * @author youcong
 *
 */
public class QueryVo{

    private List<AccountCoupon> acs;

    String[] memberId;
    
    private String couponId;
    
    /*
     * 角色编号
     */
    String[] roleNo;
    
    /**
     * 资源编号
     */
    String[] resourceNo;
    
    /**
     * 角色-资源 ID
     * @return
     */
    Integer id[];


    public Integer[] getId() {
        return id;
    }

    public void setId(Integer[] id) {
        this.id = id;
    }

    public String[] getRoleNo() {
        return roleNo;
    }

    public void setRoleNo(String[] roleNo) {
        this.roleNo = roleNo;
    }

    public String[] getResourceNo() {
        return resourceNo;
    }

    public void setResourceNo(String[] resourceNo) {
        this.resourceNo = resourceNo;
    }

    public String[] getMemberId() {
        return memberId;
    }

    public void setMemberId(String[] memberId) {
        this.memberId = memberId;
    }

    public String getCouponId() {
        return couponId;
    }

    public void setCouponId(String couponId) {
        this.couponId = couponId;
    }


    public List<AccountCoupon> getAcs() {
        return acs;
    }

    public void setAcs(List<AccountCoupon> acs) {
        this.acs = acs;
    }
    
}

 

第五种方式:

@RequestMapping(value = "/updateVersion", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    @ResponseBody
    public String updateHeadHotel(@RequestBody AppVersion appVersion) {

        Map<String, Object> map = new HashMap<String, Object>();
            logger.info(appVersion);
        try {
            logger.info("APP名字:"+appVersion.getAppName());
            // 调用数据库修改操作
            appVersion.setUpdateTime(Tools.getCurrentDate());
            appVersion.setServerFlag("1");
            appVersionService.updateById(appVersion);
            map.put("returnCode", "000000");
            map.put("message", "成功更新版本信息");
        
        }catch (Exception e) {
            // TODO: handle exception
            map.put("returnCode", "111111");
            map.put("message", "更新版本信息失败");
        
        }
        
        return JSONObject.toJSONString(map);
    }

 

第六种方式:

@RequestMapping(value="/delectHotel", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    @ResponseBody
    public Map<Object,Object> delectHotel(HttpServletRequest request) {
        
        Map<Object,Object> map = new HashMap<Object,Object>();
        
        String id = request.getParameter("id");
        logger.info("delectHotel  ===== id : " + id);
        //System.out.println("delectHotel  ===== id : " + id);
        String hotelNo = request.getParameter("hotelNo");
        logger.info("delectHotel  ===== hotelNo : " + hotelNo);
        //System.out.println("delectHotel  ===== hotelNo : " + hotelNo);
        
        try {
            
            List<Room> room_list = roomService.selectRoomByHotelNo(hotelNo.trim());
            //System.out.println("delectHotel  =====  room_list : " + room_list);
            //如果集合不为空,说明该酒店关联有房间, 不允许删除
            if(room_list != null) {
                map.put("returnMsg", "该酒店关联有房间, 不允许删除!");
                map.put("returnCode", "121212");
                return map;
            }
            
            hotelService.deleteHotelById(Integer.parseInt(id.trim()));
            //成功
            map.put("returnCode", "000000");
            map.put("returnMsg", "success");
        } catch (Exception e) {
            e.printStackTrace();
            //失败
            map.put("returnCode", "111111");
            map.put("returnMsg", "失败");
        }
        logger.info("map = " + map);
        return map;
    }

 

第七种方式:

    @RequestMapping(value="/getServiceId", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    @ResponseBody
    public Object getServiceId(HttpServletRequest request) {
        
        Map<Object,Object> map = new HashMap<Object,Object>();
        
        JSONObject json = new JSONObject();
        
        logger.info("省     ================ " +  request.getParameter("province"));
        logger.info("市     ================ " +  request.getParameter("cityname"));
        
    
        
        String city = request.getParameter("province");
        String address = request.getParameter("cityname");
        
        map.put("city", city);
        map.put("address", address);
        
        try {
            //调用数据库查询操作
            List<YuntuBase> yun_list = yuntuBaseService.selectYuntuBase(map);
            logger.info("yun_list.size() : " + yun_list.size());
            //成功
            json.put("yun_list", yun_list);
            json.put("returnCode", "000000");
            json.put("returnMsg", "success");
            return json;
        } catch (Exception e) {
            e.printStackTrace();
            //插入数据库失败,返回失败码
            json.put("returnCode", "111111");
            json.put("returnMsg", "保存失败");
            return json;
        }
        
    }

 

第八种方式:

@RequestMapping(value="/selMessageById", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    @ResponseBody
    public Object selMessageById(HttpServletRequest request) {
        
        AJAXResult result = new AJAXResult();
        
        String id = request.getParameter("id");
        logger.info("id  = " + id);
        try {
            
            Message message = messageService.selMessageById(Integer.parseInt(id.trim()));
            
            result.setData(message);
            result.setSuccess(true);
            result.setReturnCode("000000");
            result.setReturnMsg("success");
            
        } catch (Exception e) {
            e.printStackTrace();
            //查询数据库失败,返回失败码
            result.setSuccess(false);
            result.setReturnCode("111111");
            result.setReturnMsg("系统异常");
            logger.error("result = " + result);
            return result;
        }
        
        return result;
    
    }
    

 

AJAXResul代码如下:

 

package cn.pms.model;

import java.util.Map;

public class AJAXResult {
    
    private boolean success;
    
    //返回码
    private String returnCode;
    
    //返回信息
    private String returnMsg;
    
    //返回数据
    private Object data;
    
    //数据
    private Object datas;
    
    private Map<Object, Object> map;
    
    
    public boolean isSuccess() {
        return success;
    }
    public void setSuccess(boolean success) {
        this.success = success;
    }
    public String getReturnCode() {
        return returnCode;
    }
    public void setReturnCode(String returnCode) {
        this.returnCode = returnCode;
    }
    public String getReturnMsg() {
        return returnMsg;
    }
    public void setReturnMsg(String returnMsg) {
        this.returnMsg = returnMsg;
    }
    public Object getData() {
        return data;
    }
    public void setData(Object data) {
        this.data = data;
    }
    public Object getDatas() {
        return datas;
    }
    public void setDatas(Object datas) {
        this.datas = datas;
    }
    public Map<Object, Object> getMap() {
        return map;
    }
    public void setMap(Map<Object, Object> map) {
        this.map = map;
    }
    
    
}

 

 

常用AJAX请求后台数据的几种方式:

第一种:

   var id = getQueryParam("id");
    var zt = getQueryParam("zt");
    var hotelNo = getQueryParam("hotelNo");
    //alert("id = " + id + "zt = " + zt);
    $.post("/ssm_pms/selectRoomById", { id : id }, function (result){
        
        if(result.returnCode == "000000" && result.returnMsg == "success"){
            
            $("#RoomNo").val(result.room.roomNo);
            $("#Status").val(result.room.roomStatus);
        }else{
            alert("connection error");
        }
        
    });

 

第二种:

 var data = {
        floor : name,
        hotel_no : "88"
    }
    
    $.ajax({
        url : "/ssm_pms/addFloor",
        type : "POST",
        contentType: 'application/json;charset=utf-8',
        async : false,
        data : JSON.stringify(data),
        dataType : 'json',
        success : function(result){
            if(result.returnCode == "000000" && result.returnMsg == "success"){
                //window.location.href = "";
                closeWin();
                alert("添加成功");
            }else if(result.returnCode == "101011" && result.returnMsg == "重复,请重新输入"){
                alert("重复,请重新输入");
            }else{
                //showTips(3, 'Name', data.State.Errkey);
                alert("添加失败");
            }
        }
    });

Ajax的get不常用,通常$.ajax够用了,有的时候常用的也就$.post,不过目前用的最多的还是$.ajax

 

上一篇:SpringMVC数据响应方式


下一篇:Android photo color change