SpringMVC发送JSON String,使用Ajax解析

2017-04-12 19:48
    @RequestMapping("/userinfo.do")//必须返回视图
    public void getUserinfo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //这里添加用户相关session
        Users user = (Users) request.getSession().getAttribute("isLogin");
        PrintWriter write = response.getWriter();
        JSONArray jsonObj = JSONArray.fromObject(user);
        String jsonStr = jsonObj.toString();
        write.print(jsonStr);
        write.close();
    }

对应的ajax

        window.onload = function () {
            $.ajax({
                url: 'login/userinfo.do',
                type: 'GET',
                async: false,
                dataType:'JSON',
                success: function (data) {
                    var username = data[0].userName;
                    $("#user_info").text(username);
                }
            });
        }