JSON数据传输后台拿不到,求大神指点

后台代码
@RequestMapping(value="adduser")
@ResponseBody
public void adduser(String user){
System.out.println("添加");
User users=JsonUtil.deserialize(user, User.class);
System.out.println(users+"===");
}

前台代码
function register(){
alert($('.username').val()+"---");
var user={"username":$('.username').val(),"password":$('.password').val()};
alert(user.username);
$.ajax({
cache: false,
type: "POST",
dataType:'json',
url:"../../user/adduser", //把表单数据发送到userController
contentType: "application/json; charset=utf-8",
data:user, //要发送的是ajaxFrm表单中的数据
async: false,
success:function(msg){

            }

        });
        alert("注册")
    }

7个回答


    $.ajax({
        cache: false,
        type: "POST",
        dataType:'json',
        url:"../../user/adduser", //把表单数据发送到userController
        contentType: "application/json; charset=utf-8",
        data:user, //要发送的是ajaxFrm表单中的数据
        async: false,
        success:function(msg){

        }, error: function (xhr) {
            alert(xhr.responseText)///看输出什么错误
        }

    });

外面价格单引号看看

{"username":$('.username').val(),"password":$('.password').val()}

adduser方法形参换成User,ajax不设置contentType直接提交试试

修改ajax

 data:{
    user: user
}
 $.ajax({
            url: ,
            type: 'POST',
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({
                username: xxxxx,
                password: xxxxxx 
            }),
            success: function (response) {

            },
            error: function (xhr, text, error) {
            }
        });
 {"username":$('.username').val(),"password":$('.password').val()};这行不对。json格式值也要加引号,改成
 {"username":"\""+$('.username').val()+"\"","password":"\""+$('.password').val()+"\""};

你这样肯定是请求不到数据的,前台发过去的是{"username":$('.username').val(),"password":$('.password').val()};,后台却这样:public void adduser(String user)。应该是public void adduser(String username,string password);而且{"username":$('.username').val(),"password":$('.password').val()};中username和password是不需要双引号的。再有@RequestMapping(value="adduser")应该是@RequestMapping(value="/adduser"),
如果你直接在USER对象中映射JSON中的属性,应该写成public void adduser(@RequestBody User user)

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐