ajax()函数传值中文乱码解决方法介绍

摘要:
jquery的ajax()函数传值中文乱码解决方法介绍,需要的朋友可以参考下复制代码代码如下:$.ajax({ dataType:‘json',type:‘POST',url:‘http://localhost/test/test.do',data:{id:1,type:‘商品'},success:function(data){}});问题:提交后后台action程序时,取到的type是乱码解决方
jquery的ajax()函数传值中文乱码解决方法介绍,需要的朋友可以参考下 
复制代码 代码如下: 

$.ajax({ 
  dataType : ‘json',type : ‘POST',url : ‘http://localhost/test/test.do',data : {id: 1, type: ‘商品'},success : function(data){ } } ); 

问题: 
提交后后台action程序时,取到的type是乱码 
解决方法: 
方法一:提交前采用encodeURI两次编码,记住一定是两次 
1.修改以下代码 
复制代码 代码如下: 

data:{id:1, type:encodeURI(encodeURI(‘商品'))} 

2.在后台action里要对取得的字符串进行decode 
1、String type = request.getParameter(“type”); 
2、type = URLDecoder.decode(type, “UTF-8〃); 
方法二:ajax配置contentType属性,加上charset=UTF-8 
在ajax方法中加入以下参数 
contentType: “application/x-www-form-urlencoded; charset=UTF-8〃使用其它js框架或者xhr都是差不多,设置header中contentType即可, 
这里关键是charset=UTF-8,如果没有这个,是不行的,默认jQuery里的contentType是没有的 

一、测试环境 
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); 
}

免责声明:文章转载自《ajax()函数传值中文乱码解决方法介绍》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Idea中使用Redis的Java客户端和Jedis1_mongoDB最新版本4.4.1下载和安装【默认已配置存储路径和日志输出路径】下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

深入剖析jsonp跨域原理

在项目中遇到一个jsonp跨域的问题,于是仔细的研究了一番jsonp跨域的原理。搞明白了一些以前不是很懂的地方,比如: 1)jsonp跨域只能是get请求,而不能是post请求; 2)jsonp跨域的原理到底是什么; 3)除了jsonp跨域之外还有那些方法绕过“同源策略”,实现跨域访问; 4)jsonp和ajax,或者说jsonp和XMLHttpReque...

mitmproxy进行拦截

import requests from selenium import webdriver from lxml import etree import time class DiffSpider: def __init__(self): self.baseurl = 'https://www.nst.com.my/acti...

Django相关问题

遇到models模型变动后无法用migrations生成改动后的表通过以下几个方面实现1python manage.py makemigrations yourapp(你改变的app) 2python manage.py makemigrations 3python manage.py migrate pip没办法安装: 删除C:Python36Libsi...

【转载】C# MVC 实现登录的5种方式

C# MVC 实现登录的5种方式     最近悟出来一个道理,在这儿分享给大家:学历代表你的过去,能力代表你的现在,学习代表你的将来。    十年河东十年河西,莫欺少年穷。     学无止境,精益求精    小弟之前做过三月的MVC,后来又一直webForm开发,再后来,也就是现在做WPF,最近随着项目进入尾声,也就慢慢清闲了下来,清闲的时间甚是无聊,...

使用fetch进行数据请求时报json错误

使用fetch进行数据请求返回response对象,response.json报错。原因是response中含有特殊字符。 fetch(url).then(response => response.json()) .then(data => console.log(data)) .catch(e => console.log("O...

vue图表组件使用,组件文档echarts

vue图表组件使用,组件文档echarts http://echarts.baidu.com/echarts2/doc/example.html vue组件手动封装barChart.vue <template> <div :class="className" :id="id" :style="{height:height,wi...