前台返回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

 

目录
相关文章
|
1月前
|
JSON 前端开发 JavaScript
|
1月前
|
Web App开发 JSON 前端开发
Ajax实现动态及时刷新表格数据
Ajax实现动态及时刷新表格数据
38 1
|
1月前
|
存储 JSON Apache
揭秘 Variant 数据类型:灵活应对半结构化数据,JSON查询提速超 8 倍,存储空间节省 65%
在最新发布的阿里云数据库 SelectDB 的内核 Apache Doris 2.1 新版本中,我们引入了全新的数据类型 Variant,对半结构化数据分析能力进行了全面增强。无需提前在表结构中定义具体的列,彻底改变了 Doris 过去基于 String、JSONB 等行存类型的存储和查询方式。
揭秘 Variant 数据类型:灵活应对半结构化数据,JSON查询提速超 8 倍,存储空间节省 65%
|
1天前
|
JSON 数据可视化 定位技术
python_将包含汉字的字典数据写入json(将datav的全省数据中的贵州区域数据取出来)
python_将包含汉字的字典数据写入json(将datav的全省数据中的贵州区域数据取出来)
5 0
|
8天前
|
XML JSON 前端开发
|
14天前
|
存储 JSON JavaScript
「Python系列」Python JSON数据解析
在Python中解析JSON数据通常使用`json`模块。`json`模块提供了将JSON格式的数据转换为Python对象(如列表、字典等)以及将Python对象转换为JSON格式的数据的方法。
29 0
|
18天前
|
存储 JSON 数据挖掘
python逐行读取txt文本中的json数据,并进行处理
Python代码示例演示了如何读取txt文件中的JSON数据并处理。首先,逐行打开文件,然后使用`json.loads()`解析每一行。接着,处理JSON数据,如打印特定字段`name`。异常处理包括捕获`JSONDecodeError`和`KeyError`,确保数据有效性和字段完整性。将`data.txt`替换为实际文件路径运行示例。
14 2
|
1月前
|
JSON 数据格式
糊涂工具类(hutool)post请求设置body参数为json数据
糊涂工具类(hutool)post请求设置body参数为json数据
61 1
|
1月前
|
JSON 前端开发 数据格式
Ajax传递json数据
Ajax传递json数据
11 0
|
1月前
|
JSON 并行计算 API
使用CJSON/Nlohmann:快速简便地在C/C++中处理JSON数据
使用CJSON/Nlohmann:快速简便地在C/C++中处理JSON数据
148 0