Ajax异步请求结合SSM框架传输数据的几种方式

方法一
1.ajax中指定contentType为"application/json;charset=utf-8",
2.data传输的参数必须为json字符串,也就是'{"name":"tom","money":"1200"}'
3.Controller中的方法的接收参数必须采用@RequestBody接收
4.打开F12,发现传过去的参数类型是request Payload
<!--springmvc相关依赖-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context</artifactId>
  <version>5.2.4.RELEASE</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-web</artifactId>
  <version>5.2.4.RELEASE</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-webmvc</artifactId>
  <version>5.2.4.RELEASE</version>
</dependency>
<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>servlet-api</artifactId>
  <version>2.5</version>
  <scope>provided</scope>
</dependency>

<dependency>
  <groupId>javax.servlet.jsp</groupId>
  <artifactId>jsp-api</artifactId>
  <version>2.0</version>
  <scope>provided</scope>
</dependency>
<!--jackson的相关依赖-->
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-core</artifactId>
  <version>2.9.8</version>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.9.8</version>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-annotations</artifactId>
  <version>2.9.8</version>
</dependency>
<!--lombok的相关依赖-->
<dependency>
  <groupId>org.projectlombok</groupId>
  <artifactId>lombok</artifactId>
  <version>1.18.12</version>
  <scope>compile</scope>
</dependency>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
    <script src="js/jquery-1.11.0.min.js"></script>
    <script>
         $(function () {
            $("#btn_submit").click(function () {
                $.ajax({
                    url:"/account/saveAccount",
                    contentType:"application/json;charset=utf-8",
                    data:'{"name":"tom","money":"1200"}',
                    dataType:"json",
                    type:"post",
                    success:function (data) {

                    }
                })
            })
        })
    </script>
</head>
<body>
    <button id="btn_submit">提交</button>
</body>
</html>
package com.bianyiit.pojo;

import lombok.Data;

@Data
public class Account {
    private Integer id;
    private String name;
    private Double money;
}
package com.bianyiit.web;

import com.bianyiit.pojo.Account;
import com.bianyiit.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/account")
public class AccountController {

    @RequestMapping(path = "/saveAccount")
    public void saveAccount(@RequestBody Account account){
        System.out.println(account);
    }
}
方法二
1.不采用$("#regisForm").serialize()方式获取表单数据,而是通过字符串拼接的方式手写一个Json字符串,但是这种方式太繁琐,因为如果表单中的数据太多,需要一个一个手写,这不太现实
2.var name= $("#name").val(); var money=$("#money").val();
3.data类型为'{"name":"'+name+'","money":"'+money+'"}'
4.contentType为application/json;charset=UTF-8
5.后台接收需要使用@RequestBody修饰
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
    <script src="js/jquery-1.11.0.min.js"></script>
    <script>
        $(function () {
            $("#btn_submit").click(function () {
                var name= $("#name").val();
                var money=$("#money").val();
                $.ajax({
                    url:"/account/saveAccount",
                    contentType:"application/json;charset=UTF-8", 
                    data:'{"name":"'+name+'","money":"'+money+'"}',
                    dataType:"json",
                    type:"post",
                    success:function (data) {
                        
                    }
                })
            })
        })
    </script>
</head>
<body>
    <form id="regisForm">
        姓名:<input type="text" name="name" id="name">
        金钱:<input type="text" name="money" id="money">
    </form>
    <button id="btn_submit">提交</button>
</body>
</html>
package com.bianyiit.web;

import com.bianyiit.pojo.Account;
import com.bianyiit.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/account")
public class AccountController {

    @RequestMapping(path = "/saveAccount")
    public void saveAccount(@RequestBody Account account){
        System.out.println(account);
    }
}
方法三

1.正确演示过程

1.ajax中指定contentType为"application/json;charset=utf-8",
2.data传输的参数必须为json字符串,但是可以在ajax提交数据之前通过写initSerializeObject()方法初始化对象
3.data此时的传输类型为JSON.stringify($("#regisForm").serializeObject())
3.Controller中的方法的接收参数必须采用@RequestBody接收
4.打开F12,发现传过去的参数类型是request Payload,传过去的参数类型和方法一的一致
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
    <script src="js/jquery-1.11.0.min.js"></script>
    <script>
        function initSerializeObject() {
            $.fn.serializeObject = function () {
                var o = {};
                var a = this.serializeArray();
                $.each(a, function () {
                    if (o[this.name]) {
                        if (!o[this.name].push) {
                            o[this.name] = [o[this.name]];
                        }
                        o[this.name].push(this.value || '');
                    } else {
                        o[this.name] = this.value || '';
                    }
                });
                return o;
            };
        }
        $(function () {
            // 初始化、序列化对象的方法
            initSerializeObject();
            $("#btn_submit").click(function () {
                $.ajax({
                    url:"/account/saveAccount",
                    contentType:"application/json;charset=utf-8",
                    data:JSON.stringify($("#regisForm").serializeObject()),
                    dataType:"json",
                    type:"post",
                    success:function (data) {
                       
                    }
                })
            })
        })
    </script>
</head>
<body>
    <form id="regisForm">
        姓名:<input type="text" name="name" id="name">
        金钱:<input type="text" name="money" id="money">
    </form>
    <button id="btn_submit">提交</button>
</body>
</html>
package com.bianyiit.web;

import com.bianyiit.pojo.Account;
import com.bianyiit.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/account")
public class AccountController {

    @RequestMapping(path = "/saveAccount")
    public void saveAccount(@RequestBody Account account){
        System.out.println(account);
    }
}

2.错误演示过程

如果指定contentType为"application/json;charset=utf-8",指定data为JSON.stringify($("#regisForm").serialize())或者data为$("#regisForm").serialize()
那么此时提交的数据格式如下所示并且返回400
原因分析:因为后台如果指定了@RequestBody,那么接收的数据必须为json字符串格式,而我们传过去的是name=tom&money=1000,所以肯定会出错,唯一的办法就是我们自己手写一个初始化方法将其转换成{name: "tom", money: "7855"}


如果contentType中的分号也成了逗号,也就是contentType为"application/json,charset=utf-8",那么就会报415:不支持的媒体类型

方法四:这种方法应该是SSM框架结合异步提交表单中最常用的方式
设置contentType为application/x-www-form-urlencoded
设置data为$("#regisForm").serialize()
在Controller里面的方法接收的参数不能使用RequestBody修饰
此时前端传输的参数放在data form中
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
    <script src="js/jquery-1.11.0.min.js"></script>
    <script>
        $(function () {
            $("#btn_submit").click(function () {
                $.ajax({
                    url:"/account/saveAccount",
                    contentType:"application/x-www-form-urlencoded", 
                    data:$("#regisForm").serialize(),
                    dataType:"json",
                    type:"post",
                    success:function (data) {
                        
                    }
                })
            })
        })
    </script>
</head>
<body>
    <form id="regisForm">
        姓名:<input type="text" name="name" id="name">
        金钱:<input type="text" name="money" id="money">
    </form>
    <button id="btn_submit">提交</button>
</body>
</html>
package com.bianyiit.web;

import com.bianyiit.pojo.Account;
import com.bianyiit.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/account")
public class AccountController {
	//这里千万别用@RequestBody修饰接收的参数
    @RequestMapping(path = "/saveAccount")
    public void saveAccount(Account account){
        System.out.println(account);
    }
}

方法四和方法一、二、三不同,方法一二三提交的格式是request Payload,方法四提交的格式是Form Data

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值