ajax获取后台返回的json

 

  先贴一张后台返回前台的json格式:

####1.登录

/user/login.do post(代码需要post方式请求),开放get,方便调试

request

username,password

response

fail

{
    "status": 1,
    "msg": "密码错误"
}

success

{
    "status": 0,
    "data": {
        "id": 12,
        "username": "aaa",
        "email": "[email protected]",
        "phone": null,
        "role": 0,
        "createTime": 1479048325000,
        "updateTime": 1479048325000
    }
}

后台返回代码:

 /**
     * 用户登录
     *
     * @param username
     * @param password
     * @param session
     * @return
     */

    @RequestMapping(value = "login.do",method = RequestMethod.POST)
    @ResponseBody
    public ServiceResponse login(String username, String password, HttpSession session) {
        //这个ServiceResponse高复用的接口类 由状态位,message,data组成
        ServiceResponse response = iUserService.login(username,password);
        if (response.isSuccess()){
           session.setAttribute(Const.CURRENT_USER,response.getData());
        }
        return response;
    }

前端ajax访问后台代码:

$.ajax(
                {
                    url: "/user/login.do",
                    type: "post",
                    datatype: "json",
                    data: {
                        "username": username,
                        "password": password
                    },
                    success: function (response) { //返回的结果自动放在resut里面了
                        //在回调函数种执行交互流程
                        if (response['status'] == 0) {
                            alert('登录成功!')
                            var data = response['data'];
                            console.log(response['status'])
                            console.log(response['msg'])
                            console.log(data['id'])
                            console.log(data['username'])
                            console.log(data['password'])
                            console.log(data['email'])
                            console.log(data['phone'])
                            sessionStorage.setItem("username",data['username']);
                            var url="main2.html";
                            window.open(url,"_parent")

                        } else {
                            alert(response['msg'])
                        }
                    }
                });

 

你可能感兴趣的:(ajax)