struts2中ajax前端从后台获取中文乱码问题

1、

使用scriptCharset即可解决问题,用contentType就不一定可以了。

复制代码代码如下:

$.ajax({ 
      url: testUrl, 
      dataType: 'jsonp', 
      type: 'post', 
      scriptCharset: 'utf-8'
    });

上面的解决方案是最完美的,另外也附上网上的解决方式吧,是用contentType来处理的

2、

复制代码代码如下:

jQuery(form).ajaxSubmit({ 
url: "ajax.aspx?a=memberlogin", 
type: "post", 
dataType: "json", 
contentType: "application/x-www-form-urlencoded; charset=utf-8", 
success: showLoginResponse 
});

3、在action中设置编码格式时注意 :

response.setContentType("text/html;charset=gbk");一定要写在writer= response.getWriter(); 之前,否则依然乱码

 PrintWriter writer ;
try {

response.setContentType("text/html;charset=gbk");
writer= response.getWriter();
writer.write(sb.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();

}

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

非常感谢http://yjingzeming.iteye.com/blog/1536335大大的分享;

4、当不使用printwriter时可以使用json格式进行传参

推荐使用JSON,可以参考以下代码
action:
  Map<String,Object> map = new HashMap<String,Object>();
            map.put( "total",total);
           map.put( "list", list);
            json = JSONObject. fromObject(map);
            try {
                 /*设置编码格式,返回结果
                 * ***/
                response.setContentType( "text/html;charset=UTF-8");
                response.getWriter().write( json.toString());
           } catch (IOException e1) {
                e1.printStackTrace();
           }


Jsp页面中用ajax请求后台:
$.ajax(
      url:
      method:
     success:function(data){
     var list = data.list;  //获取后台list
}
);

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值