AJAX POST乱码问题

    技术2022-05-20  74

    由于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")); %>


    最新回复(0)