JSP中使用JSON传递参数出现中文乱码

代码如下:


        Map<String,Object> map = new HashMap<>();

        if("admin".equals(username) && "123".equals(password)) {
    
    
            map.put("success",true);
            map.put("message","登录成功");
            req.getSession().setAttribute("username",username);
        }else {
    
    
            map.put("success",false);
            map.put("message","登录失败");
        }
        resp.getWriter().write(JSON.toJSONString(map));
function login() {
    
    
        $.ajax({
    
    
            type: 'POST',
            url: '/chat/login',
            dataType: 'json',
            data: {
    
    
                username: $("#username").val(),
                password: $("#password").val()
            },
            success: function (data) {
    
    
                if (data.success) {
    
    
                    window.location.href = "index.jsp";
                } else {
    
    
                    alert(data.message);
                }
            }
        });
    }

在这里插入图片描述


将Map转换成JSON格式时,需要设置ContentType

resp.setContentType("text/html;charset=utf-8");

猜你喜欢

转载自blog.csdn.net/swy66/article/details/109672300