现象:ajax提交数据给java tomcat服务端,服务端接收到的数据,返回到客服端显示为乱码,雨相同的中文相比较也不正确。
原因分析:
1, web客服端html源文件存储编码问题。
例如源文件中的中文常量存储为ANSI编码格式(可以用记事本另存选择编码格式,再用ultraedit看,hex代码明显不同),你ajax设置为按utf-8发送,这时肯定会出乱。
2,服务端接收编码设置问题。
例如:tomcat中将目录conf下的server.xml中的
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
加上URIEncoding="utf-8"变成
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
就解决了。
注意版本:jre8,tomcat7.2
总结:网上ajax有N多种解决方法,我都试了个遍,什么encodeURI两次,调用java服务端的URLDecode都不行。
只有这种方法可行,也许是版本问题吧!反正解决方法就是什么文件编码、ajax:contentText设置,服务端配置字符编码统统设置为UTF-8就可以了!
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=gb2312">
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Cache-Control" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="0">
<title>Initialize Value for ComboGrid - jQuery EasyUI Demo</title>
<link rel="stylesheet" type="text/css" href="media/css/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="media/css/themes/icon.css">
<script type="text/javascript" src="media/js/jquery.min.js"></script>
<script type="text/javascript" src="media/js/jquery.easyui.min.js"></script>
<script type="text/javascript" src="media/js/xmlhttpfun.js"></script>
<script language="javascript">
$(document).ready(function(){
$("#b01").click(function(){
htmlobj=$.ajax({url:"http://192.168.1.105:8080/ServletHello/ServletHello",contentType:"application/x-www-form-urlencoded;charset=utf-8",cache:false,data:{q:$("#txtStr").val()},async:false});
alert((htmlobj.responseText));
//alert(getText("fun.asp"));
});
});
</script>
</head>
<body>
<h2>Initialize Value for ComboGrid</h2>
<p>Initialize value when ComboGrid is created.</p>
<div style="margin:20px 0"></div>
<input class="easyui-combogrid" style="width:250px" value="EST-12" data-options="
panelWidth: 500,
idField: 'uid',
textField: 'username',
url: 'fun.asp',
method: 'get',
mode:'remote',
columns: [[
{field:'uid',title:'用户ID',width:80},
{field:'username',title:'用户名',width:120}
]],
fitColumns: true
">
<input name="b01" type="button" id="b01" value="测试">
<input name="txtStr" type="text" id="txtStr">
</body>