XMLHttpRequest的POST中文表單問題解決方案


XMLHttpRequest的POST中文表單問題解決方案
由於XMLHttpRequest POST的內容是用UTF-8編碼,所以在服務端要先把request的編碼改為UTF-8.
而且客戶端post的表單是x-www-form-urlencoded的,所以也要對post的內容進行編碼encodeURIComponent()函數
escape() 只是為 ASCII字符 做轉換工作,轉換成的 %unnnn 這樣的碼,如果要用更多的字符如 UTF-8字符庫
就一定要用 encodeURIComponent() 或 encodeURI() 轉換才可以成 %nn%nn
還有
escape() 不編碼這些字符:  @*/+
encodeURI() 不編碼這些字符:  !@#$&*()=:/;?+'
encodeURIComponent() 不編碼這些字符:  !*()'
還是推薦使用encodeURIComponent()函數來編碼比較好。
代碼如下:
在客戶端的js腳本
<script>
function myXMLHttpRequest(){
 var xmlHttp = false;
 try {
  xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
 } catch (e) {
  try {
   xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
  } catch (e2) {
   xmlHttp = false;
  }
 }
 if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
  xmlHttp = new XMLHttpRequest();
 }
 return xmlHttp;
}
  content = "user="+encodeURIComponent("大發");
  xmlHttp.Open("POST", "doc.jsp", false);
  xmlHttp.setRequestHeader("Content-Length",content.length);
  xmlHttp.setRequestHeader("CONTENT-TYPE","application/x-www-form-urlencoded");
  xmlHttp.Send(content);
</script>
JSP
<%@page language="java" contentType="text/html;charset=gbk"%>
<%
 request.setCharacterEncoding("UTF-8");
 System.out.println(request.getParameter("user"));
%>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM