AJAX 編碼問題分析

來源:互聯網
上載者:User

1、 要發送的內容

格式:xml;編碼:utf-8

AJAX

編碼:utf-8(req.getCharacterEncoding();讀出用戶端編碼為utf-8)

servlet

編碼:預設(request位設定編碼)

結果:

//注意:tempContent輸出未標明正常的,均為不正常log.debug("encoding=" + encoding); //encoding=utf-8log.debug("tempContent=" + tempContent); //正常                        log.debug("3tempContent=" + new String(tempContent.getBytes("gb2312"),"gb2312")); //正常           log.debug("5tempContent=" + new String(tempContent.getBytes("UTF-8"),"UTF-8")); //正常             log.debug("8tempContent=" + new String(tempContent.getBytes("UTF-8"),"ISO8859-1")); //正常



下面代碼為XML內容產生代碼:

 function makeXmlTemp() { var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");xmlDoc.async = false;var p = xmlDoc.createProcessingInstruction("xml","version=\"1.0\" encoding=\"utf-8\"");xmlDoc.appendChild(p);var root = xmlDoc.createElement('ocr');xmlDoc.appendChild(root); //alert(xmlDoc.xml);var str = xmlDoc.xml;str = str.replace('?>', ' encoding=\"utf-8\"?>');return str;}

下面代碼為AJAX 發送代碼:

//AJAX請求,使用同步方法function ajaxRequest(url, param, method){     var xmlHttp;       var rs;       var isie = true;      if(window.ActiveXObject){           xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");           isie = true;       }else if(window.XMLHttpRequest){           xmlHttp = new XMLHttpRequest();       }       try{           if(isie == false ){               xmlHttp.open("GET", url, false);               xmlHttp.overrideMimeType("text/html;charset=gb2312");               xmlHttp.send(null);               //alert(xmlHttp.responseText);              alert("只支援IE!");        }else{                        if(method == 'POST'){                                xmlHttp.open("POST", url, false);                  xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");                 xmlHttp.send(param);                             }else{                xmlHttp.open("GET", url, false);                xmlHttp.send(null);                             }                              if(xmlHttp.readyState == 4){                           if (xmlHttp.status == 200 || xmlHttp.status == 0){                       return xmlHttp.responseText;                  }             }           }       }catch(exception){           alert('exception!');        //alert('exception:'+exception.message);       }}      var tempDat = makeXmlTemp();//alert('tempDat=' + tempDat);        $i('txtTempFields').value = tempDat;           var tempUrl = url.getURI();alert(tempUrl);var params = 'tempName=' + tempName + '&tempContent=' + encodeURIComponent(tempDat);var echo = ajaxRequest(tempUrl, params,'POST');alert(echo);

下面為servlet 代碼:

void doPost(HttpServletRequest req, HttpServletResponse resp)        throws ServletException, IOException {    String encoding = req.getCharacterEncoding();    log.debug("encoding=" + encoding);    //req.setCharacterEncoding("utf-8");        try {        String tempName    = req.getParameter("tempName");        String tempContent = req.getParameter("tempContent");                String rv = SUCCESS;        log.debug("tempName=" + tempName);                log.debug("tempContent=" + tempContent);                            log.debug("1tempContent=" + new String(tempContent.getBytes("ISO8859-1"),"gb2312"));                log.debug("2tempContent=" + new String(tempContent.getBytes("UTF-8"),"gb2312"));                log.debug("3tempContent=" + new String(tempContent.getBytes("gb2312"),"gb2312"));                            log.debug("4tempContent=" + new String(tempContent.getBytes("ISO8859-1"),"UTF-8"));                log.debug("5tempContent=" + new String(tempContent.getBytes("UTF-8"),"UTF-8"));                  log.debug("6tempContent=" + new String(tempContent.getBytes("gb2312"),"UTF-8"));                            log.debug("7tempContent=" + new String(tempContent.getBytes("ISO8859-1"),"ISO8859-1"));                log.debug("8tempContent=" + new String(tempContent.getBytes("UTF-8"),"ISO8859-1"));                log.debug("9tempContent=" + new String(tempContent.getBytes("gb2312"),"ISO8859-1"));                tempContent = URLDecoder.decode(tempContent,"UTF-8");                log.debug("8tempContent=" +URLDecoder.decode(tempContent,"UTF-8"));}      catch (Exception e) {         e.printStackTrace();log.error("savaTempData failed.", e);     }}

2、 要發送的內容:

格式:xml;編碼:gb2312

AJAX

編碼:utf-8(req.getCharacterEncoding();讀出用戶端編碼為utf-8)

servlet

編碼:預設(reqest未設定編碼)

結果:

log.debug("encoding=" + encoding); //encoding=utf-8log.debug("tempContent=" + tempContent); //正常                        log.debug("3tempContent=" + new String(tempContent.getBytes("gb2312"),"gb2312")); //正常                        log.debug("5tempContent=" + new String(tempContent.getBytes("UTF-8"),"UTF-8")); //正常            log.debug("8tempContent=" + new String(tempContent.getBytes("UTF-8"),"ISO8859-1")); //正常 

可以看出後台能正確解碼與XML的編碼無關。

3、 要發送的內容:

格式:xml;編碼:gb2312

AJAX

編碼:位設定(req.getCharacterEncoding();讀出用戶端編碼為null)

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


servlet

編碼:預設(reqest未設定編碼)

結果:

     log.debug("encoding=" + encoding); //encoding=null            
     log.debug("4tempContent=" + new String(tempContent.getBytes("ISO8859-1"),"UTF-8"));  //正常

4、 要發送的內容:

格式:xml;編碼:gb2312

AJAX

編碼:位設定(req.getCharacterEncoding();讀出用戶端編碼為null)

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

servlet

編碼:

  req.setCharacterEncoding("utf-8"); //或者使用下面的語句            //req.setCharacterEncoding("ISO8859-1");

結果:

與3相同。可見,req指定編碼並不能正常輸出,需要轉碼。並且和使用encodeURIComponent()與否無關(使用一次)。

5、 要發送的內容:

格式:xml;編碼:gb2312

AJAX

編碼:gbk(req.getCharacterEncoding();讀出用戶端編碼為gbk)

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

servlet

編碼:

        req.setCharacterEncoding("utf-8"); //或者使用下面的語句            //req.setCharacterEncoding("ISO8859-1");

結果:

均不能正常解碼。

總結

通過實驗可以看出,AJAX post資料的編碼和資料本身無關,和SERVLET是否設定編碼無關:

req.setCharacterEncoding("utf-8")

僅和AJAX使用的編碼有關,並且只能是utf-8(不是utf-8有可能嗎?):

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

若自己封裝AJAX函數時,不要忘記指定字元集屬性:charset=utf-8

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.