ajax json 处理返回值方法,附带中文乱码解决方案

来源:互联网 发布:蓝月传奇官印数据 编辑:程序博客网 时间:2024/05/21 09:45

java中转换成json对象方法:

public JSONObject toJsons(Object o) {

//HttpServletResponse response = (HttpServletResponse)ServletActionContext.getResponse();
ActionContext ctx = ActionContext.getContext();
HttpServletResponse response = (HttpServletResponse) ctx.get(ServletActionContext.HTTP_RESPONSE);
response.setCharacterEncoding("utf-8");
response.setContentType("application/json;charset=utf-8");
JsonConfig jsonConfig = new JsonConfig();
JSONObject jo = JSONObject.fromObject(o,jsonConfig);
return jo;

}

此处;一定加上转换编码:并且得在out前加;

response.setContentType("application/json;charset=utf-8");
 PrintWriter out=response.getWriter();


如果用 $.ajax({
type : "get",
url : "actionname.action?pc=+"+pid+"&sc="+sid+"&flag="+flag,
async : false,

contentType: "application/x-www-form-urlencoded; charset=utf-8", 

success : function(data) {
$("#mainajax").html(data);
}
         });

方式传值,调用的是jquery里面的方法,pid,sid等内容是中文时,后台有可能解析成乱码。此时,只需要后台如此处理:pid.getBytes("ISO-8859-1"),"utf-8")。因为jquery中默认的contentype字符集是ISO-8859-1。如果不加红色字体部分,那么浏览器的不同会导致中文汉字解析异常。ie中后台需写:pid.getBytes("ISO-8859-1"),"gb2312")。火狐,谷歌,360,sara等需写:pid.getBytes("ISO-8859-1"),"utf-8")。



0 0