jQuery 发送 post 请求返回字符串乱码的解决

本文介绍了一种解决前后端交互时中文乱码的方法,通过配置响应头和输出流编码来确保中文正常显示。具体实现包括前端使用jQuery发起POST请求,并设置响应类型为JSON,后端则采用SpringMVC框架处理请求并返回处理后的评论列表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

后端代码:

@RequestMapping(params ="method=getCommentsBySentence",method= RequestMethod.POST)
public void getCommentsBySentence(Map<String,Object> map,@RequestParam String essayContextStr,HttpServletResponse response) throws Exception {
    String sentencesCommentListStr = null;
    try {
        List<Map> sentencesCommentList = getCommentsBySentence(essayContextStr.replace("’", "'").trim());
        sentencesCommentListStr = JSON.toJSONString(sentencesCommentList);
    } catch (Exception e) {
        logger.error("",e);
    }

    response.setCharacterEncoding("utf-8");
    response.setContentType("text/html;charset=utf-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();  //输出中文,这一句一定要放到response.setContentType("text/html;charset=utf-8"),  response.setHeader("Cache-Control", "no-cache")后面,否则中文返回到页面是乱码
    out.print(sentencesCommentListStr);
    out.flush();
    out.close();
}

前端代码:

$.post("${ctx}/WritingEssayAction.action?method=getCommentsBySentence",{
            "essayContextStr":"${essayContextStr}"
        },function(data){
            alert(data);
        });

参考资料:
Spring–SpringMVC3.1的ResponseBody返回字符串乱码问题解决-百联达-ITPUB博客
http://blog.itpub.net/28624388/viewspace-768058

jQuery AJAX 请求乱码 返回乱码 - hongweigg的专栏 - 博客频道 - youkuaiyun.com
http://blog.youkuaiyun.com/hongweigg/article/details/6756278

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值