Jquery ajax 提交序列化或JSON数据到后台

前端提交序列化数据

  • 前端代码
html 复制代码
$.ajax({
	url: "/user/add",
	type: "post",
	dataType: "json",
	data: {
	    user : $('#form').serialize()
	},
	success: function (result) {
	}
})
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/1f9a7611c2c84249bc317b0b6813af07.png)
  • 后台代码
java 复制代码
@ResponseBody
@RequestMapping("/add")
public Msg form(User user){
	userDao.insert(user); // 添加一条信息
}

前端提交json格式数据

  • 前端代码
html 复制代码
//定义serializeObject方法,序列化表单
function serializeObject(form) {
    let obj = {};
    let a = form.serializeArray();
    $.each(a, function () {
        if (obj[this.name]) {
            if (!obj[this.name].push) {
                obj[this.name] = [obj[this.name]];
            }
            obj[this.name].push(this.value || '');
        } else {
            obj[this.name] = this.value || '';
        }
    });
    return obj;
}

$.ajaxSetup({
    contentType: 'application/json',
});


/**
 * 添加修改数据,提交表单
 * @param path
 * @param aim
 */
function doAddUpdate(path, aim) {
    //阻止表单自动提交
    $("#addUpdateForm").submit(function () {
        return false;
    });
    let obj =  serializeObject($("#addUpdateForm"));
    $.post(path, JSON.stringify(obj), function (data) {
        if (data.code == 200) {
            alert(data.msg);
            window.location.href = aim;
        } else {
            alert(data.msg);
        }
    });
}

<button onclick="doAddUpdate('user/doAddUpdate','user/list')">post数据</button>
  • 后台代码
java 复制代码
@PostMapping("/doAddUpdate")
public ResultBean doAddUpdate(@RequestBody User user) {

}
相关推荐
wtsolutions1 天前
Understanding JSON Formats - What JSON to Excel Supports
json·excel
wtsolutions1 天前
Advanced Features - Unlocking the Power of JSON to Excel Pro
linux·json·excel
wtsolutions1 天前
Real-World Use Cases - How Organizations Use JSON to Excel
json·excel
wtsolutions1 天前
Introduction to JSON to Excel - The Ultimate Conversion Tool
json·excel
San30.1 天前
LangChain 第二课:拒绝“废话”,用 Zod 强制 AI 输出标准 JSON
人工智能·langchain·json
wtsolutions1 天前
JSON to Excel WPS Add-in - Perfect for WPS Office Users
json·excel·wps
wtsolutions1 天前
Flat vs Nested JSON Conversion - Deep Dive into Conversion Modes
json
weixin_462446231 天前
【实战】Java使用 Jsoup 将浏览器书签 HTML 转换为 JSON(支持多级目录)
java·html·json·书签
alonewolf_991 天前
Redis Stack全面解析:从JSON存储到布隆过滤器,打造高性能Redis扩展生态
数据库·redis·json
梦6502 天前
JavaScript (ES5)+ES6+jQuery 核心对象方法大全
javascript·es6·jquery