这是jsp的页面,数据提交到doPost,然后响应到div里面显示,但是 AJAX中的中文数据提交到Servlet 始终是乱码;怎么改啊,大神们。。。
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<!-- 引入写了AJAX的js文件 -->
<script type="text/javascript" src="${pageContext.request.contextPath }/AJAXDemo02POST/ajax_posttext.js"></script>
<title>Insert title here</title>
</head>
<body>
<h1>AJAX POST获取数据的练习</h1>
<div style="width:300px;height:200px;border:1px solid red;" id="divajax"></div>
<input type="button" value="点我获取数据" onclick="ajaxPostText()"/>
</body>
</html>
这是 写了AJAX的js的文件
function ajaxPostText(){
// 创建异步对象:
var xhr = createXMLHttp();
// 设置监听:
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if(xhr.status == 200){
document.getElementById("divajax").innerHTML = xhr.responseText;
}
}
}
// 打开路径:
xhr.open("POST","/AJAXDemo01/AJAXDemo01Servlet",true);
//这一句没能将提交到post的中文数据编码改掉
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
// 发送请求:
xhr.send("name=张三&pass=密码");
}
function createXMLHttp() {
var xmlHttp;
try { // Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
} catch (e) {
try {// Internet Explorer
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
}
}
}
return xmlHttp;
}
这是Servlet代码
public class AJAXDemo01Servlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {//未完成
request.setCharacterEncoding("UTF-8");
String pass =request.getParameter("pass");
String name = request.getParameter("name");
response.setContentType("text/html;charset=UTF-8");
response.getWriter().println(
"名称是:" + name + "密码是:" + pass);
System.out.println("名称是:" + name + "密码是:" + pass);
}
}