由于ajax数据发送数据编码方式为UTF-8,所以在发送传送汉字是会出现乱码。
解决方法:
(1)jsp页面
例
var text=document.getElement("text");
text=escape(escape(text));
text 为传送的汉字,escape为javascript自带编码函数
(2)获取数据的后台java代码
- public static String unescape(String src)
- {
- StringBuffer tmp = new StringBuffer();
- tmp.ensureCapacity(src.length());
- int lastPos=0,pos=0;
- char ch;
- while (lastPos<src.length())
- {
- pos = src.indexOf("%",lastPos);
- if (pos == lastPos)
- {
- if (src.charAt(pos+1)=='u')
- {
- ch = (char)Integer.parseInt(src.substring(pos+2,pos+6),16);
- tmp.append(ch);
- lastPos = pos+6;
- }
- else
- {
- ch = (char)Integer.parseInt(src.substring(pos+1,pos+3),16);
- tmp.append(ch);
- lastPos = pos+3;
- }
- }
- else
- {
- if (pos == -1)
- {
- tmp.append(src.substring(lastPos));
- lastPos=src.length();
- }
- else
- {
- tmp.append(src.substring(lastPos,pos));
- lastPos=pos;
- }
- }
- }
- return tmp.toString();
- }
public static String unescape(String src)
{
StringBuffer tmp = new StringBuffer();
tmp.ensureCapacity(src.length());
int lastPos=0,pos=0;
char ch;
while (lastPos<src.length())
{
pos = src.indexOf("%",lastPos);
if (pos == lastPos)
{
if (src.charAt(pos+1)=='u')
{
ch = (char)Integer.parseInt(src.substring(pos+2,pos+6),16);
tmp.append(ch);
lastPos = pos+6;
}
else
{
ch = (char)Integer.parseInt(src.substring(pos+1,pos+3),16);
tmp.append(ch);
lastPos = pos+3;
}
}
else
{
if (pos == -1)
{
tmp.append(src.substring(lastPos));
lastPos=src.length();
}
else
{
tmp.append(src.substring(lastPos,pos));
lastPos=pos;
}
}
}
return tmp.toString();
}
unescape 用于解码
使用 String str=unescape(request.getParameter("text"));