【www.gdgbn.com--php函数】

利用js escape函数解决中文乱码问题

本来网页特效中的escape()是将中文按iso-8859-1字符集进行url编码的,那样通过 request.getparameter()是能直接获取到请求参数的,但后来的javascript将escape()换成了unicode字符集编 码,如此一来,在jsp教程和servlet中就没法直接拿到请求参数了,具体原因我也不知道。

 解决办法:

        1、首先对中文字符进行两次escape()编码,如要传参数name,值为“你好”,则url的格式为....name=escape(escape("你好")),这样一来,在request.getparameter()就能取到编码后的参数了。

        2、由于取到的参数是  %25u4f60%25u597d  格式的,没法用常规的urldecoder.decode()来进行解码,还好,这世上的牛人够多,在网上直接找到了一个工具类,能实现 javascript中escape()及unescape()式的编解码

 

<script language="javascript"> 
function get(id){return document.getelementbyid(id).value}
function setting()
  {
   var xmlhttp;
 if(window.activexobject)
 {
  xmlhttp=new activexobject("microsoft.xmlhttp")
 }else{
   xmlhttp=new xmlhttprequest();
 }
 xmlhttp.onreadystatechange=function()
 {
    if(xmlhttp.readystate==4)
    {
       if(xmlhttp.status==200)
    {
       alert("成功!")
    }else{
      alert(xmlhttp.status)
    }
    }
   }
 var url="action.asp教程?action=setting&rnd="+math.random()
 xmlhttp.open("post",url,true)
 var senddate ="title="+escape(get("title"))+"&conn_way="+escape(get("conn_way"))+"&databasename="+escape(get("databasename"))+"&sqlusername="+escape(get("sqlusername"))+"&sqlpassword="+escape(get("sqlpassword"))+"&sqllocalname="+escape(get("sqllocalname"))+"&pg_size="+escape(get("pg_size"))+"&adminid="+escape(get("adminid"))+"&adminpwd="+escape(get("adminpwd"));
2727 xmlhttp.setrequestheader("content-type","application/x-www-form-urlencoded");
 xmlhttp.send(senddate)
  }
</script>

上面的实例我们中文只用了escape函数,语法如下

定义和用法
escape() 函数可对字符串进行编码,这样就可以在所有的计算机上读取该字符串。

语法
escape(string)参数 描述
string 必需。要被转义或编码的字符串。

返回值
已编码的 string 的副本。其中某些字符被替换成了十六进制的转义序列。

说明
该方法不会对 ascii 字母和数字进行编码,也不会对下面这些 ascii 标点符号进行编码: - _ . ! ~ * " ( ) 。其他所有的字符都会被转义序列替换。
提示和注释
提示:可以使用 unescape() 对 escape() 编码的字符串进行解码。

注释:ecmascript v3 反对使用该方法,应用使用 decodeuri() 和 decodeuricomponent() 替代它

 

本文来源:http://www.gdgbn.com/jiaocheng/29582/