jquery中文乱码的多种解决方法


Posted in Javascript onJune 21, 2013

1、使用$.ajax出现的中文乱码的解决方案:

var _realname = $("input[name='_searchName']").val(); 
    var termcourseId = '<%=termid%>'; 
    var classId = '<%=classid%>'; 
    var url = "/addressbook/studentListNoPage.do"; 
    //var dataUrl = "formMap.TERMCOURSE_ID="+termcourseId+"&formMap.CLASS_ID="+classId+"&formMap.IS_ONLINE=all&formMap.REALNAME="+_realname; 
    $.ajax({ 
           type: "POST", 
           url: url, 
           dataType:"json", 
           data: { 
               "formMap.TERMCOURSE_ID":termcourseId, 
               "formMap.CLASS_ID":classId, 
               "formMap.IS_ONLINE":"all", 
               "formMap.REALNAME":encodeURI(_realname) 
           }, 
           contentType: "application/x-www-form-urlencoded; charset=utf-8", 
           success: function(data){ 
               data = eval(data); 
               var html = ""; 
               $("#allUnselectedUser").html(html); 
           }, 
           error : function(XMLHttpRequest, textStatus, errorThrown){ 
               alert(textStatus); 
           } 
        });

其中当使用dataUrl中的&方式提交时,无论前台是使用encodeURI或者encodeURIComponent又或者escape把中文转码,提交到Action中都是乱码,并不是想要的%e6%b1%89%e5%ad%97这种转后编码。即使加上contentType也不行。

把dataUrl中的&方式提交修改为data:{name:value}的方式提交即可。

在Action中使用URLDecoder.decode(realname, "UTF-8")来转码即可转换为中文了。使用UTF-8是因为Jquery的提交方式默认为UTF-8,即使把contentType中的charset修改其他,例如GBK,后台也把UTF-8修改GBK,都不能正确转换。

jQuery ajax乱码问题解决
一、测试环境
jQuery:1.3.2
tomcat:5.5.17
二、测试方法
1.使用get方式
服务器端java代码:

String name = new String(request.getParameter("name").getBytes("iso8859-1"),"utf-8");

客户端js代码:
$.ajax({url: "2.jsp",type: "get",data: {name:"中文"},success: function(response){
        alert(response);
}});

结果:正确显示
$.ajax({url: "2.jsp",type: "get",data: "name=中文",success: function(response){
        alert(response);
}});

结果:乱码
$.get("2.jsp", { name: "中文" },function(response){
    alert(response);
});

结果:正确显示
$.get("2.jsp", "name=中文",function(response){
    alert(response);
});

结果:乱码

2.post方式
服务器端java代码:

request.setCharacterEncoding("UTF-8"); 
String name = request.getParameter("name");

客户端js代码:
$.ajax({url: "3.jsp",type: "post",data: "method=testAjaxPost&name=中文",success: function(response){
    alert(response);
}});

结果:正确显示
$.ajax({url: "3.jsp",type: "post",data: {name:"中文"},success: function(response){
    alert(response);
}});

结果:正确显示
$.post("3.jsp", { name: "中文" },function(response){
    alert(response);
});

结果:正确显示
$.post("3.jsp", "name=中文",function(response){
    alert(response);
});

结果:正确显示
三、使用filter
public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    if (req.getHeader("X-Requested-With") != null && req.getHeader("X-Requested-With").equalsIgnoreCase("XMLHttpRequest")) {
        request.setCharacterEncoding("utf-8");
    } else {
        request.setCharacterEncoding("gbk");
    }
    chain.doFilter(request, response);
}

jQuery在使用ajax的时候会在header中加入X-Requested-With,值为:XMLHttpRequest,filter中判断是jQuery的ajax请求时就把字符编码设为utf8,这样可以解决post提交中的中文乱码问题,不需要在代码中设置request.setCharacterEncoding("UTF-8");
对于get方式的中文乱码问题,建议不使用get方式提交中文,统统改为post ^-^

为了和prototype.js处理中文的方式一致,可以使用如下的方式,自定义header中的属性RequestType

$.ajax({
    url: "3.jsp",
    type: "post",
    data: {name:"中文"},
    beforeSend: function(XMLHttpRequest){
        XMLHttpRequest.setRequestHeader("RequestType", "ajax");
        alert("开始");
    },
    success: function(data, textStatus){
        alert(data);
    },
    error: function(XMLHttpRequest, textStatus, errorThrown){
        alert("错误:" + textStatus);
    },
    complete: function(XMLHttpRequest, textStatus){
        alert("完成:" + textStatus);
    }
 });
 

filter代码如下:
public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    if (req.getHeader("RequestType") != null && req.getHeader("RequestType").equalsIgnoreCase("ajax"))) {
        request.setCharacterEncoding("utf-8");
    } else {
        request.setCharacterEncoding("gbk");
    }
    chain.doFilter(request, response);
}
Javascript 相关文章推荐
用javascript实现给图片加链接
Aug 15 Javascript
javascript Select标记中options操作方法集合
Oct 22 Javascript
新鲜出炉的js tips提示效果
Apr 03 Javascript
为原生js Array增加each方法
Apr 07 Javascript
JavaScript 模块化编程(笔记)
Apr 08 Javascript
纯css实现窗户玻璃雨滴逼真效果
Aug 23 Javascript
js窗口震动小程序分享
Nov 28 Javascript
React-router 4 按需加载的实现方式及原理详解
May 25 Javascript
详解vue前后台数据交互vue-resource文档
Jul 19 Javascript
JavaScript页面倒计时功能完整示例
May 15 Javascript
jQuery pager.js 插件动态分页功能实例分析
Aug 02 jQuery
Vue toFixed保留两位小数的3种方式
Oct 23 Javascript
js单向链表的具体实现实例
Jun 21 #Javascript
javascript setTimeout和setInterval计时的区别详解
Jun 21 #Javascript
js简易namespace管理器 实例代码
Jun 21 #Javascript
JavaScript中的this关键字介绍与使用实例
Jun 21 #Javascript
js验证模型自我实现的具体方法
Jun 21 #Javascript
JS验证控制输入中英文字节长度(input、textarea等)具体实例
Jun 21 #Javascript
无缝滚动js代码通俗易懂(自写)
Jun 19 #Javascript
You might like
PHP系列学习之日期函数使用介绍
2012/08/18 PHP
PHPAnalysis中文分词类详解
2014/06/13 PHP
PHP基于工厂模式实现的计算器实例
2015/07/16 PHP
php ucwords() 函数将字符串中每个单词的首字符转换为大写(实现代码)
2016/05/12 PHP
php版微信自定义回复功能示例
2016/12/05 PHP
CCPry JS类库 代码
2009/10/30 Javascript
一个简单的js动画效果代码
2010/07/20 Javascript
JavaScript+html5 canvas绘制缤纷多彩的三角形效果完整实例
2016/01/26 Javascript
jQuery解析XML 详解及方法总结
2016/09/28 Javascript
js鼠标移动时禁止选中文字
2017/02/19 Javascript
angular4 JavaScript内存溢出问题
2018/03/06 Javascript
angular2路由之routerLinkActive指令【推荐】
2018/05/30 Javascript
nodejs之koa2请求示例(GET,POST)
2018/08/07 NodeJs
Javascript删除数组里的某个元素
2019/02/28 Javascript
浅谈 Webpack 如何处理图片(开发、打包、优化)
2019/05/15 Javascript
p5.js码绘“跳动的小正方形”的实现代码
2019/10/22 Javascript
js、jquery实现列表模糊搜索功能过程解析
2020/03/27 jQuery
vue-amap根据地址回显地图并mark的操作
2020/11/03 Javascript
vue实现图片裁剪后上传
2020/12/16 Vue.js
[45:17]DOTA2-DPC中国联赛定级赛 Phoenix vs DLG BO3第三场 1月9日
2021/03/11 DOTA
python操作数据库之sqlite3打开数据库、删除、修改示例
2014/03/13 Python
Python输出汉字字库及将文字转换为图片的方法
2016/06/04 Python
查看python下OpenCV版本的方法
2018/08/03 Python
Python实现的爬取小说爬虫功能示例
2019/03/30 Python
django 通过URL访问上传的文件方法
2019/07/28 Python
用python生成与调用cntk模型代码演示方法
2019/08/26 Python
Python任务调度利器之APScheduler详解
2020/04/02 Python
Python延迟绑定问题原理及解决方案
2020/08/04 Python
重构Python代码的六个实例
2020/11/25 Python
canvas绘制文本内容自动换行的实现代码
2019/01/14 HTML / CSS
可打印的优惠券、杂货和优惠券代码:Coupons.com
2018/06/12 全球购物
研究生导师推荐信
2015/03/25 职场文书
酒店财务总监岗位职责
2015/04/03 职场文书
Python中Permission denied的解决方案
2021/04/02 Python
世界十大儿童漫画书排名,法国国宝漫画排第五,第二是轰动日本连环
2022/03/18 欧美动漫
Win11怎么添加用户?Win11添加用户账户的方法
2022/07/15 数码科技