最近在研究AJAX是,自己做了一个程序测试,发现在使用get方式提交时,如果参数中有中文的话,会出现乱码问题,而且取回的XMLHttpRequest.resopnseText中如果有中文,将其值在页面上显示后也是乱码。Google一下,发现大多是针对post方式提交的解决办法,
于是自己通过查看别人的文章,下来后自己调试,解决了get方式提交中文参数乱码的问题:
我的环境是表单页面index.html的编码是UTF-8:下面是我的代码:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Demo1.html</title>
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<!-- HTTP 1.1 -->
<meta http-equiv="Cache-Control" content="no-store"/>
<!-- HTTP 1.0 -->
<meta http-equiv="Pragma" content="no-cache"/>
<!-- Prevents caching at the Proxy Server -->
<meta http-equiv="Expires" content="0"/>
<script language="javascript">
var httpRequest=null;
function createHttpRequest() {
if(window.XMLHttpRequest) {
return new XMLHttpRequest();
}
else if(window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHTTP");
if(!request) {
request = new ActiveXObject("Msxml2.XMLHTTP");
}
return request;
}
}
function ok() {
var url = "handel.jsp?name="+encodeURIComponent(document.form1.name.value);
httpRequest = createHttpRequest();
httpRequest.onreadystatechange = aa;
httpRequest.open("GET",url,true);
httpRequest.send(null);
}
function aa(){
if(httpRequest.readyState == 4) {
if(httpRequest.status == 200) {
document.getElementById("hh").innerText = httpRequest.responseText;
}
}
}
</script>
</head>
<body>
<form name="form1">
<input type="text" size="24" name="name">
<input type="button" value="提交" onclick="ok()"><br>
你输入了:<textarea rows="3" cols="20" readonly id="hh"></textarea>
</form>
</body>
</html>
在构造url是用javascript自带的encodeURIComponent方法将参数进行编码,下面是我的代码
var url = "handel.jsp?name="+encodeURIComponent(document.form1.name.value);
httpRequest = createHttpRequest();
httpRequest.onreadystatechange = aa;
httpRequest.open("GET",url,true);
httpRequest.send(null);
在目的地的handel.jsp页面(该页面显示编码也是UTF-8)上,先用iso-8859-1将request.getparameter()方法取回的参数值,转成字节串,
然后在用UTF-8将字节串转成字符串,就好了,下面是handel.jsp的代码:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>为了解决返回值XMLHttpRequest.resopnseText中文乱码的问题,需要设置下面这句话:
response.setHeader("Charset","UTF-8");