数据插入成功,为什么ajax返回的是error函数

代码:
//发送注册异步请求

    $.ajax({
        type:"post",
        url :"/user/register",
        data:$("form").serialize(),
        dataType:"json",
        success:function(data){
            alert(data);
            if(data == "success"){
                alert("注册成功");
                window.location.href="/";//你跳转的页面
            }else if(data == "fail"){
                alert("注册失败:"+data);
            }

        },
        error:function(data){
            alert("error:"+data);
            if(data == "error")
            alert("注册异常"+data);
            window.location.href="/";
        }
    });

@RequestMapping(value = "/user/register",method = RequestMethod.POST)

public ModelMap register(User user){
    ModelMap map = new ModelMap();
    try {
        System.err.print(user.toString());
        int result = userService.register(user);
        if (result > 0) {
            //注册成功
            map.put("res","success");
        }else {
            map.put("res","fail");
        }
        return map;
    }catch (Exception e){
        e.printStackTrace();
        map.put("data","error");
        return map;
    }
}

而且window.location.href="/";这行代码也没执行,因为没有跳转

clipboard.png
数据库是插入了数据的,也没有抛出异常,为什么会是error呢?

阅读 3.6k
5 个回答

看一下response,http code是否为200,不是的话就会进入error逻辑

ajax设置了dataType:"json"
返回格式不是json 就会进error

新手上路,请多包涵

控制层返回的不是json格式,你少了@ResponseBody吧

浏览器F12,查看NetWork中的请求,你会发现Status Code: 404 Not Found。

为什么是404?因为你方法上没加@ResponseBody注解,方法把返回结果当成了一个路径,它找不到页面就报404.

然后你方法加上@ResponseBody注解,成功运行项目后,发现又会报HTTP Status 500 - Request processing failed; nested exception is java.lang.IllegalArgumentException: No converter found for return value of type: class org.springframework.ui.ModelMap。
为什么?json类型转换失败。

应该怎么做?fastjson或jackson可以了解一下。
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题