Js编码和Java后台解码
Js中,使用get提交,url传递参数的时候,会带来中文乱码的问题,对此可以使用js的函数encodeURI(href);来解决。
一、Js编码的几种方式区别:
1、window.escape()与HttpUtility.UrlEncodeUnicode()编码格式一样:将一个汉字编码为%uxxxx格式
不会被window.escape编码的字符有:@ _ - . * / + 这与http://www.w3school.com.cn/js/jsref_escape.asp上的解释不符合
2、window.encodeURIComponent()与HttpUtility.UrlEncode()编码格式一样:将一个汉字编码为%xx%xx%xx的格式
不会被window.encodeURIComponent编码的字符有:' ( ) * - . _ ! ~ 这与http://www.w3school.com.cn/js/jsref_encodeURIComponent.asp解释相符合
不会被HttpUtility.UrlEncode编码的字符有:' ( ) * - . _ ! 相比较而言,HttpUtility.UrlEncode比window.encodeURIComponent多一个 ~ 编码
3、window.encodeURI编码(常用这种方法), 不会被window.encodeURI编码的字符有: - _ . ! * ( ) ; / ? : @ & = $ , #,与encodeURIComponent对比,发现encodeURI不对:;/?:@&=+$,#这些用于分隔 URI 组件的标点符号进行编码
例:
function zhuanma(){ var name = document.getElementById("name").value; var pass = document.getElementById("pass").value; name = window.encodeURI(name); var url = "<%=request.getContextPath()%>/user/userlogin.action?name="+name+"&pass="+pass+"; window.open(url,'','width=800,height=250,top=80,left=70,location=no,status=no,scrollbars=yes,resizable=yes'); } } String name = java.net.URLDecoder.decode(name,"UTF-8");
window.self.location="searchbytext.action?searchtext="+encodeURIComponent(encodeURIComponent(seartext));
searchtext=java.net.URLDecoder.decode(searchtext,"UTF-8");/*需要处理异常*/
String s = new String(request.getParameter("name").getBytes("ISO8859-1"), "UTF-8");