SpringMVC中使用ajax

SpringMVC处理JSON数据中介绍了SpringMVC如何返回一个json对应的对象或者数组。这篇将介绍一下,SpringMVC在使用ajax时的几种情况。

测试一:发送get请求,不带参数

实验代码:
实体类:Employ

public class Employ {
    private String userName;
    private int age;

    @Length(min = 3, max = 5)
    private String hobby;

    private double salary;
    private double height;

    @JsonIgnore
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date birth;
    //get、post、toString、构造方法,这里就省略了
    }

controller 层的方法

	@ResponseBody
    @RequestMapping(value = "/testAjaxGet", method = RequestMethod.GET)
    public Employ testAjaxGet() {
        return new Employ("花花牛", 20, "吃草", 118, 12.5);
    }

jsp页面

<body>
<% pageContext.setAttribute("path", request.getContextPath()); %>
<a href="#" class="test1">get</a><br>
</body>
<script type="text/javascript">
    $(function(){
        $(".test1").click(function () {
            $.ajax({
                url:"${path}/testAjaxGet",
                type:"GET",
                success:function (data) {
                    console.log(data)
                }
            })
            return false;
        });
</script>

测试二:发送get请求,带参数

controller层

	@ResponseBody
    @RequestMapping(value = "/testAjaxGet1", method = RequestMethod.GET)
    public Employ testAjaxGet1(Employ employ){
        System.out.println(employ);
        return employ;
    }

jsp页面

// 发送get请求带参方式一,data是js对象,会自动以xxx=XXX&yyy=YYY的形式拼接到url后
        $(".test2").click(function () {
            $.ajax({
                url:"${path}/testAjaxGet1",
                type:"GET",
                data:{name:"花花牛",age:18,hobby:"吃草",salary:153},
                success:function (data) {
                    console.log(data)
                }
            })
            return false;
        })

当在发送这个请求时,在浏览器中可以看到请求的地址,是自动将data中的数据已xxx=XXX&yyy=YY的形式自动拼接
在这里插入图片描述
而这个请求中,数据是
在这里插入图片描述
get方式的ajax请求,传参还可以直接在url后拼接数据

    $.ajax({
                url:"${path}/testAjaxGet1?name=花花牛&age=123&salary=123.23&hobby=吃草",
                type:"GET",
                success:function (data) {
                    console.log(data)
                }
            })
            return false;
        })

测试三:发送post请求,不带参数

controller层

    @ResponseBody
    @RequestMapping(value = "/testAjaxPost", method = RequestMethod.POST)
    public Employ testAjaxPost(){
        return new Employ("花花牛", 20, "吃草", 118, 12.5);
    }

jsp页面

<body>
<% pageContext.setAttribute("path", request.getContextPath()); %>
<a href="#" class="test1">Post without params</a><br>
<a href="#" class="test2">test POST method with params</a>
</body>
<script type="text/javascript">
    $(function () {
        $(".test1").click(function () {
            $.ajax({
                url:"${path}/testAjaxPost",
                type:"POST",
                success:function (data) {
                    console.log(data)
                }
            })
            return false;
        });
</script>

测试四:发送post请求,带参数

第一种格式,直接发送js对象作为参数

controller层
 	@ResponseBody
    @RequestMapping(value = "/testAjaxPost1", method = RequestMethod.POST)
    public Employ testAjaxPost1(Employ employ){
        return employ;
    }

jsp页面

$(".test2").click(function () {
            $.ajax({
                url:"${path}/testAjaxPost1",
                type:"POST",
                data:{userName:"花花牛",age:18,hobby:"吃草",salary:12.23,height:123.321},
                success:function (data) {
                    console.log(data)
                }
            })
            return false;
        })

当这个请求发送时,对应的请求头的信息
在这里插入图片描述
数据的格式
在这里插入图片描述
这种情况下,如果后端的方法参数是实体类,会自动映射装配,如果实体类标注了@RequestBody,这时就会报错,错误信息如下:
在这里插入图片描述

如果使用@RequestBody标注的是一个String类型,则获取的数据格式是这样的

	@ResponseBody
    @RequestMapping(value = "/testAjaxPost1", method = RequestMethod.POST)
    public String testAjaxPost1(@RequestBody String employ){
        System.out.println(employ);
        return employ;
    }

在控制台打印的结果是:在这里插入图片描述你会发现他是乱码的

第二种格式,发送json字符串作为参数

使用ajax发送json字符串作为参数,需要指定contentType为 application/json,否则会报错

controller层

	@ResponseBody
    @RequestMapping(value = "/testAjaxPost1", method = RequestMethod.POST)
    public String testAjaxPost1(@RequestBody String employ){
        System.out.println(employ);
        return employ;
    }

jsp层

$(".test2").click(function () {
            var obj = {userName:"花花牛",age:18,hobby:"吃草",salary:12.23,height:123.321};
            var objString = JSON.stringify(obj);
            $.ajax({
                url:"${path}/testAjaxPost1",
                type:"POST",
                data:objString,
                contentType:"application/json",
                success:function (data) {
                    console.log(data)
                }
            })
            return false;
        })

此时请求的数据格式是
在这里插入图片描述
如果后端方法的参数是String类型,并且标注了@RequestBody注解,则获得的值是
在这里插入图片描述这就解决了第一种方式使用String类型接收乱码问题。

如果此时使用实体类作为参数,并且没有使用@RequestBody注解

@ResponseBody
    @RequestMapping(value = "/testAjaxPost1", method = RequestMethod.POST)
    public Employ testAjaxPost1(Employ employ){
        System.out.println(employ);
        return employ;
    }

控制台打印的是
在这里插入图片描述
表明前端传输的数据,后端接收不到。
如果加了@RequestBody注解

  	@ResponseBody
    @RequestMapping(value = "/testAjaxPost1", method = RequestMethod.POST)
    public Employ testAjaxPost1(@RequestBody Employ employ){
        System.out.println(employ);
        return employ;
    }

控制台打印的是
在这里插入图片描述
可以接收到数据。

使用ajax发送数据,数据的格式是字符串,如果不指定 contentType 为 application/json,则在请求中,数据的格式是:
在这里插入图片描述
此时,如果后端的接口,实体类参数标注了@RequestBody ,就会报错,如果没有添加这个注解,不报错,但是无法获取到前端传递的值。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值