• ajax请求, 前后端, 代码示例


    【博客园cnblogs笔者m-yb原创,转载请加本文博客链接,笔者github: https://github.com/mayangbo666,公众号aandb7,QQ群927113708】

    https://www.cnblogs.com/m-yb/p/9965238.html

    ajax是一种前端异步发送请求数据到后端,进行数据交互的手段,前端页面使用ajax需要依赖jQuery的js库.

    比如前端页面提交form表单的数据的ajax请求代码片段示例:

    点击登录按钮,触发onlick函数 login()

    <script>
    function login() {
    $.ajax({
    type: "POST",
    dataType: "json",
    url: "/login",
    data: {
    loginCode: $("#loginCode").val(),
    password: $("#password").val()
    },
    success: function (dataResult) {
    if (!dataResult.success){
    alert(dataResult.message);
    return false;
    }
    alert("登录成功");
    window.location.href = "/toMainPage";
    },
    error: function (XMLHttpResponse) {

    }
    });
    }
    </script>

    后端的AjaxVO代码:

    public class AjaxVO {
    
    private boolean success; private String message; private Object data; private AjaxVO(){ } private AjaxVO(boolean success, String message, Object data){ this.success = success; this.message = message; this.data = data; } public static AjaxVO success(){ return new AjaxVO(true, null, null); }
    public static AjaxVO success(){
    return new AjaxVO(true, null, null);
    }

    public static AjaxVO success(Object data){
    return new AjaxVO(true, null, data);
    }

    public static AjaxVO failed(String message){
    return new AjaxVO(false, message, null);
    }
    public boolean isSuccess() {
    return success;
    }

    public String getMessage() {
    return message;
    }

    public Object getData() {
    return data;
    }
    }

    使用时, 如果后端需要返回无数据体的成功状态就调用

    AjaxVO.success();

    如果后端需要返回有数据体的成功状态就调用

    AjaxVO.success(Object data);

    返回失败信息:
    AjaxVO.failed(String message);
    【注】:
    需要解析json的依赖,本文使用了jackson:
    需要 引入Jackson Core, Jackson Databind,Jackson Annotations三个mavenjar包依赖.
  • 相关阅读:
    linux下tomcat内存溢出
    leetcode
    HDU 4810 Wall Painting (位操作-异或)
    详解Java中的访问控制修饰符(public, protected, default, private)
    mpvue开发微信小程序之时间+日期选择器
    多行文本溢出隐藏
    swift 多态函数方式
    swift 多态函数方式
    swift 多态函数方式
    swift 多态函数方式
  • 原文地址:https://www.cnblogs.com/m-yb/p/9965238.html
Copyright © 2020-2023  润新知