(java)jsp页面ajax发出请求返回json格式数据 中文乱码问题

后台代码:
Map<String, String> items = new HashMap<String,String>();
items.put("name", "李连杰");
items.put("sex", "男");
JSONObject jo = JSONObject.fromObject(items);
try {
PrintWriter out = response.getWriter();
response.setContentType("text/json; charset=UTF-8");
out.write(jo.toString());
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
前台代码:
$.ajax({
type : "post",
url : "salary/queryFormulaValueById.action",
data : "formulaID=" + formula,
dataType:"json",
success : function(items) {
alert(items.name);
},
beforeSend : function() {
$("#formulamsg").html("查询中...");
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert("内部错误,请重新操作!");
}
});
页面头信息:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

success函数里面得到的items.name老是乱码(全是问号),实在无法解决,哪位大神能解决?不胜感激!!

你如果没有使用编码集过滤器,
就需要手动设置response的编码集
response.setCharacterEncoding("UTF-8");
这句话要放在这个方法的最前面,就是设置返回头的前面
如果页面传入的参数,在获取时乱码,则需要
request.setCharacterEncoding("UTF-8");
温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-05-25
setContentType要放在PrintWrite前面,你颠倒了
第2个回答  推荐于2017-10-15
加个
$.ajax({
contentType : "application/json",});本回答被提问者采纳
第3个回答  2013-05-25
response.setContentType()语句放在hashMap前面试试看
相似回答