测试的是ajax in practice第一章中的hello2.jsp+hello2.html。
当我在文本框中输入中文时,返回的页面中出现了乱码
最后解决的方法时:
1、tomcat的conf/server.xml中添加编码:
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"
URIEncoding="utf-8" />
<filter>
<filter-name>Set Character Encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Set Character Encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>html中使用utf-8
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<jsp:directive.page contentType="text/html;charset=utf-8" pageEncoding="UTF-8"/>
var name = $('helloTxt').value;
name = encodeURI(name);
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("name");
name = java.net.URLDecoder.decode(name,"utf-8");在完成这些操作后,经过测试,IE6/Opera9.5/Firefox2中均未再出现参数乱码的现象。
但是很奇怪的是,这些浏览器都不能自动识别hello2.html为utf-8,而是识别为ISO-8859-1。所以显示为乱码。但是提交后,返回的那些新文字却是正常显示:
最终发现:因为测试系统搭建时引入了struts2,并且在struts.properties中加入了如下一行“struts.locale=en_GB”。去掉或者修改为“struts.locale=zh_GB”一切都正常了。
完整的代码如下:
1、hello2.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Hello Ajax version 2</title>
<style type="text/css">...
*{...}{font-family:Tahoma, Arial, sans-serif;}
#helloTitle{...}{color:#48f;}
</style>
<script type="text/javascript" src="js/prototype-1.6.0.2.js"></script>
<script type="text/javascript">...
window.onload=function()...{
$('helloBtn').onclick=function()...{
var name = $('helloTxt').value;
//alert(escape(name));
//alert(encodeURI(name));
name = encodeURI(name);
//alert(name);
new Ajax.Request(
"hello2.jsp?name=" + name,
...{
method:"get",
onComplete:function(xhr)...{
$('helloTitle').innerHTML = xhr.responseText;
}
}
);
};
};
</script>
</head>
<body>
<div id="helloTitle">
<h1>您好,陌生人</h1>
</div>
<p>请在下方的文本框中输入您的姓名来介绍您自己:</p>
<input type="text" size="24" id="helloTxt" />
<button id="helloBtn">提交</button>
</body>
</html>
<jsp:directive.page contentType="text/html;charset=utf-8" pageEncoding="UTF-8"/><%...
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("name");
name = java.net.URLDecoder.decode(name,"utf-8");
%><h1>您好 <%=name%></h1>
<p>我过去认识一个叫 <b><i><%=name%></i></b> 的,是您吗?</p>
546

被折叠的 条评论
为什么被折叠?



