当前位置: 代码迷 >> Java Web开发 >> xmlhttp.send()传值中文乱码,该如何处理
  详细解决方案

xmlhttp.send()传值中文乱码,该如何处理

热度:577   发布时间:2016-04-17 00:44:52.0
xmlhttp.send()传值中文乱码
jsp 页面
<%@ page language="java" contentType="text/html; charset=GBK"
  pageEncoding="GBK"%>
<!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=GBK">
<title>Insert title here</title>
</head>
<script type="text/javascript">
function ajaxFunction()
{
  var xmlHttp=null;
  if(window.ActiveXObject)
  {
  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  else if(window.XMLHttpRequest)
  {
  xmlHttp=new XMLHttpRequest();
  }
  return xmlHttp;
}
function senddata()
{
var xmlHttp=ajaxFunction();
var url = "../TestInput";
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttp.send(("a='王'"));
}

</script>
<body>
<button onclick="senddata()">点击传递数据 </button>
</body>
</html>


TestInput的 servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  //这里是获取参数的
String data=request.getParameter("a");

InputStream stream=request.getInputStream();
InputStreamReader isr=new InputStreamReader(stream);
BufferedReader br=new BufferedReader(isr);
String str=br.readLine(); 
str=str.replace("a=", "");
System.out.println(str.getBytes()[0]+" "+str.getBytes()[1]+" "+str.getBytes()[2]);
System.out.println("王".getBytes("iso-8859-1")[0]);
System.out.println(str);
str=URLDecoder.decode(str,"utf-8");
System.out.println(str);
br.close();


}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}

tomcat 的server.xml 关键部分
  <Connector port="8086" protocol="HTTP/1.1" 
  connectionTimeout="20000" 
  redirectPort="8443"
useBodyEncodingForURI="true" URIEncoding="gbk"/>

因为程序 是用 json 传值的,传递到服务器的数据太多 数据不能放在url 中,只能放在send()中
不要把数据封装成 xml 格式的
能解决把100分给他

------解决方案--------------------
http://blog.csdn.net/niuniu20008/article/details/6842904
------解决方案--------------------
要明白乱码的根因是由于编码格式不一致导致的,所以只要你所有的编码格式都统一应该不会出现乱码:

把所有的编码搞一致,都用UTF-8好了。
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="GBK"%>
<!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">

System.out.println("王".getBytes("UTF-8")[0]);
System.out.println(str);
str=URLDecoder.decode(str,"UTF-8");

<Connector port="8086" protocol="HTTP/1.1" 
connectionTimeout="20000" 
redirectPort="8443"
useBodyEncodingForURI="true" URIEncoding="UTF-8"/>
  相关解决方案