zoukankan      html  css  js  c++  java
  • 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"));
    %>
  • 相关阅读:
    网络编程之Tcp,udp
    网络编程简介
    面向对象之高级篇 反射,元类
    面向对象 高级篇
    面向对象,继承
    初识面向对象
    包 hashlib,logging
    模块
    Dango生命周期回顾与forms组件
    Django中auth登录、注册、修改密码、退出、ORM自关联
  • 原文地址:https://www.cnblogs.com/shaoshao/p/3397689.html
Copyright © 2011-2022 走看看