zoukankan      html  css  js  c++  java
  • Ajax json交互和SpringMVC中@RequestBody

    Ajax json交互和SpringMVC中@RequestBody

    标签:


    背景

    自己提供出去得接口中参数设置为@RequestBody VipPromotionLog vipPromotionLog为一个对象。但是前端人员得处理方式代码如下

        var data = {
            "userId" : 20142100122,
            "userOperationStep" : 2,
            "appPlatform": "android",
            "app" : 0,
            "videoId":123123
        };
    
        $.ajax({
            url : 'http://localhost:81/online-2c/api/vippromotion',
            type : 'POST',
            dateType : 'json',
            data:data,
            success : function(msg){
                console.log(msg);
            }
        })
    

    问题出现

    上述情况出现如图一错误

    图一
    ![](https://i.loli.net/2018/12/11/5c0f5111df916.png)

    排查

    查看这从请求得类型如图二

    图二
    ![](https://i.loli.net/2018/12/11/5c0f5121e26b9.png)

    content-Type为application/x-www-form-urlencoded
    而且传输过去的类型是一个对象,那么我们设置的@RequestBody需要的是什么,难道不是一个对象。这里我个人的理解为@RequestBody需要传输过去的是一个字符串并且和其注释的对象的属性一一对应。

    解决

    办法一

    有两种办法解决 第一不改变后台代码的情况下解决办法如下代码

        var data = {
            "userId" : 20142100122,
            "userOperationStep" : 2,
            "appPlatform": "android",
            "app" : 0,
            "videoId":123123
        };
    
        $.ajax({
            url : 'http://localhost:81/online-2c/api/vippromotion',
            type : 'POST',
            dateType : 'json',
            contentType : 'application/json',
            data:JSON.stringify(data),
            success : function(msg){
                console.log(msg);
            }
        })
    

    application/json 传输过去的数据为json对象的字符串,data为一个对象,用JSON.stringify转换成对象字符串,其实上面代码和下面的是一样的

       var data = '{
    ' +
            '        "userId" : 20142100122,
    ' +
            '        "userOperationStep" : 2,
    ' +
            '        "appPlatform": "android",
    ' +
            '        "app" : 0,
    ' +
            '        "videoId":123123
    ' +
            '    }';
    
        $.ajax({
            url : 'http://localhost:81/online-2c/api/vippromotion',
            type : 'POST',
            dateType : 'json',
            contentType : 'application/json',
            data:data,
            success : function(msg){
                console.log(msg);
            }
        })
    

    办法二

    修改后台代码,去除@RequestBody注解。这样的话你传输过去的就是一个对象了,并一一对应,如果没有的话就为空。前端js代码不变。

    防止

    根据前后端的数据交互类型来进行选择。

  • 相关阅读:
    AtCoder Beginner Contest 167
    AtCoder Beginner Contest 166
    AtCoder Beginner Contest 165
    AtCoder Beginner Contest 164
    AtCoder Beginner Contest 163
    AtCoder Beginner Contest 162
    AtCoder Beginner Contest 161
    AtCoder Beginner Contest 160
    AtCoder Beginner Contest 159
    自定义Mybatis自动生成代码规则
  • 原文地址:https://www.cnblogs.com/Krloypower/p/9277117.html
Copyright © 2011-2022 走看看