开发者社区> youcongtech> 正文
阿里云
为了无法计算的价值
打开APP
阿里云APP内打开

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

简介: 我个人开发常用的如下所示: 之所以像下面这样下,一是前台Ajax,二是为安卓提供接口数据 现在常用的是返回JSON数据,XML的时代一去不复返 JSON相对于XML要轻量级的多 对JSON不是十分熟悉的可参考此网站:http://www.
+关注继续查看

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

之所以像下面这样下,一是前台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

 

版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

相关文章
windows python flask返回json数据
windows python flask返回json数据
0 0
SpringMVC 使用@ResponseBody返回json 中文乱码
SpringMVC 使用@ResponseBody返回json 中文乱码
0 0
fastadmin设置默认返回json类型
fastadmin设置默认返回json类型
0 0
【SpringBoot】55、SpringBoot处理404异常返回JSON数据
我们如果要对 404 返回的异常信息做重新定义,我们需要新建一个 controller 来处理它
0 0
springMvc48-返回json数据
springMvc48-返回json数据
0 0
Django响应JsonResponse返回json格式数据报错
Django响应JsonResponse返回json格式数据报错
0 0
Django返回json数据
Django返回json数据
0 0
controller发送请求接收返回json
controller发送请求接收返回json
0 0
java面试题:返回Json用什么注解?
java面试题:返回Json用什么注解?
0 0
+关注
youcongtech
热爱生活,热爱编程,乐于分享,善于总结。
文章
问答
文章排行榜
最热
最新
相关电子书
更多
低代码开发师(初级)实战教程
立即下载
阿里巴巴DevOps 最佳实践手册
立即下载
冬季实战营第三期:MySQL数据库进阶实战
立即下载