---
title: "AJAX中文乱码的几种后台的解决方案"
author: "semicolon"
date: "2009-06-15T14:00:56Z"
tags: []
slug: "ajax"
draft: false
lastmod: "2009-06-15T14:00:56Z"
id: 408619
url: "https://codingbug.iteye.com/blog/408619"
---

1、使用POST方式传参

```javascript

 sPara += sName + "=" + encodeURI(encodeURI(sValue)) + "&";
 xmlHttp.onreadystatechange = handleStateChange;	
 xmlHttp.open( "POST" , sURL , true );
 xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
	
 xmlHttp.send(sPara);

```

<span style="color:red">
注意，这里我使用了两次encodeURI，encodeURI(encodeURI(sValue))
</span>


```java

String providerName = request.getParameter("providerName");
 //post 传递的时候,一定是用utf8编码的
providerName = URLDecoder.decode(providerName , "utf-8");

```


分析：当调用request.getParameter()函数时，会自动进行一次URI的解码过程，调用时内置的解码过程会导致乱码出现。而URI 编码两次后，request.getParameter()函数得到的是原信息URI编码一次的内容。再用可控的解码函数 java.net.URLDecoder.decode()就可解出原始的正确的信息。

2、使用GET方式传参
GET方式要比POST方法好转码，但是它有字符限制
有两种方式
一、在后台添加unescape方法进行解码
前台使用javascript的escape方法进行转码

```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();
 }


```


二、直接使用encodeURI进行转码
前台直接使用encodeURI进行转码
在后台使用request.getParameter("name");就可以得到原始数据。
原因可能是，当调用request.getParameter()函数时，程会自动进行一次URI的解码过

这几种方式都主要用于，前台向后台传数据，后台向前台转数据没有描述

<span style="color:red">
注：文章主要用于自己的经验积累，所以没有写的太细，如有人来看，看不懂也不要骂我啊
</span>