Ajax發送請求時的編碼問題

對於咱們大多數作web開發的人來講,在不一樣編碼影響下,每每會出現亂碼的問題,以至於最終達不到開發需求。若是發送的請求裏不包含非西歐字符,將不會有任何問題;可是一旦包含了非西歐字符的請求參數,問題也就出現了,但也不必定。 javascript

如今有這樣一個小demo: html

show.jsp: java

<% @ page contentType="text/html;charset=GBK" language="java" %> web

<%       // 服務器從頁面獲取用戶的name請求參數,在控制檯輸出 數組

    System.out.println(request.getParameter("name")); 瀏覽器

%> 緩存

first.html: 服務器

<input type="text" id="test" name="name"><br /> app

<input type="button" value="GET發送" onclick='getSend(document.getElementById("test").value)' /> 異步

<input type="button" value="POST發送" onclick='postSend(document.getElementById("test").value)' />

<script type=javascript>

   // 獲取xmlHttpRequest

  var xmlHttp;

  function getXMLHttpRequest()

 {

   if(window.XMLHttpRequest)

  {

     xmlHttp = new XMLHttpRequest();

 }else if(window.ActiveXObject)

  {

    try{

       xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");

      }catch(e){

       try{

            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

           }catch(e){ }

   } 

 }

 }

  function postSend(name)

  {

    xmlHttp = getXmlHttpRequest;

   // 服務器請求url

   var uri = "show.jsp";

 // 使用POST方式打開與服務器的鏈接

  xmlHttp.open("POST",uri,true);    // true----指定使用異步處理

  xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

 // 發送請求

  xmlHttp.send("name="+name);

  }

fucntion getSend(name)

{

  xmlHttp = getXmlHttpRequest;

  var uri = "show.jsp?name="+name;

  xmlHttp.open("GET",uri,true);

  xmlHttp.send(null);

}

</script>

當咱們訪問頁面提交請求參數後,會在控制檯看到,使用GET請求則出現了中文亂碼。Ajax請求中,對於POST請求較好處理,異步POST請求參數默認採用UTF-8字符集來編碼請求參數,所以只須要調用HttpServletRequest的setCharacterEncoding("utf-8");就能夠解決。通常狀況下,服務器頁面默認採用UTF-8字符集來解碼請求參數,因此有時候會看到,即便你沒有設置編碼字符集,也會看到正確的輸出。

可是GET就有所不一樣,咱們知道,GET將請求參數和對應的值附加在請求的URL以後。對於中文請求參數值,不會以中文的方式傳遞參數值,而是轉碼成URL的格式。因此,應當在服務器頁面中做出如下修改:

<%

  if(request.getMethod().equalsIgnoreCase("POST"))

  {

     request.setCharacterEncoding("utf-8");

    System.out.println(request.getParameter("name")); 

  }

 // 處理GET請求

  if(request.getMethod().equalsIgnoreCase("GET"))

  {

     String temp = reqeust.getParameter("name");

// 將參數按ISO-8859-1字符集編碼成字節數組,而後按UTF-8字符集將該字節數組解碼成字符串

    String new_string = new String(temp.getBytes("ISO-8859-1"),"UTF-8");

   System.out.println(new_string); 

  }

 %> 

這樣,或許能夠看到正確的GET發送參數的輸出,可是當咱們換用IE瀏覽器發出請求時,將再次出現亂碼。GET請求參數所用的字符集與客戶端瀏覽器有關,不一樣的瀏覽器在發送GET請求時使用了不一樣的字符集。

因此,咱們只能使用java.net.URLEncoder.encode()方法進行處理:

java.net.URLEncoder.encode(請求參數,"GBK");

而後在服務器端進行相應的轉換處理:

new String(請求參數.getBytes("ISO-8859-1"),"GBK");

這樣GET發送請求參數亂碼問題就解決了。可是,會有至關煩瑣的一系列操做,不推薦。

最好是使用POST發送請求參數,理由以下:

1 當請求參數包含的數據太多時,GET請求可能 丟失請求參數

2 當兩次GET請求參數相同時,Internet Explorer將直接使用服務器上次的緩存,不會從新發送請求,這對於自動刷新頁面至關很差。

相關文章
相關標籤/搜索