来源于(
http://bbs.java.ccidnet.com/htm_data/15/0612/224185.html)
xmlhttp request传值时我们时常碰到乱码问题,但只要采用encodeURIComponent(参数) 就不会有乱码了,不用utf-8传值在非IE下将会显示乱码。
提交form时,我们可以先给form里的参数全部用encodeURIComponent处理下。如(post时):
Var params="";
for(var i=0;i<thisform.elements.length;i++){
var elem=thisform.elements;
params+=(elem.name+"="+encodeURIComponent(elem.value.trim()));
if(i!=(thisform.elements.length-1))params+="&";
}
通过encodeURIComponent(参数)传递的值,js下用decodeURIComponent解码取值。但decodeURIComponent处理不了页面是gbk编码的urlencode()这样的数据(这个非常麻烦,好像需要对每个gbk字符专门处理才行,如果页面全部是utf-8的就没有问题了)。
后台如果是gbk编码的话,那不能直接用 urldecode()解用encodeURIComponent传递来的值,而需要转换成utf-8。如
Java:
String word="";
if (request.getParameter("word")!=null){
word=request.getParameter("word");
//word = new String(word.getBytes("ISO-8859-1"),"GBK");这样传值,在使用xmlHTTP取值时可能会乱码,因为ff传递使用的是Uniocde编码;
/*如果js里用到了encodeURIComponent(query),就用下面这种方式取值;兼容任何编码和浏览器*/
word=java.net.URLDecoder.decode(word);
word = new String(word.getBytes("ISO-8859-1"),"UTF-8");
}
Php:
$word="";
if(!Empty($_POST["word"])){
$word = $_POST["word"].trim();
$word = iconv("utf-8", "gbk",urldecode($word));
}
xmlhttp request传值时我们时常碰到乱码问题,但只要采用encodeURIComponent(参数) 就不会有乱码了,不用utf-8传值在非IE下将会显示乱码。
提交form时,我们可以先给form里的参数全部用encodeURIComponent处理下。如(post时):
Var params="";
for(var i=0;i<thisform.elements.length;i++){
var elem=thisform.elements;
params+=(elem.name+"="+encodeURIComponent(elem.value.trim()));
if(i!=(thisform.elements.length-1))params+="&";
}
通过encodeURIComponent(参数)传递的值,js下用decodeURIComponent解码取值。但decodeURIComponent处理不了页面是gbk编码的urlencode()这样的数据(这个非常麻烦,好像需要对每个gbk字符专门处理才行,如果页面全部是utf-8的就没有问题了)。
后台如果是gbk编码的话,那不能直接用 urldecode()解用encodeURIComponent传递来的值,而需要转换成utf-8。如
Java:
String word="";
if (request.getParameter("word")!=null){
word=request.getParameter("word");
//word = new String(word.getBytes("ISO-8859-1"),"GBK");这样传值,在使用xmlHTTP取值时可能会乱码,因为ff传递使用的是Uniocde编码;
/*如果js里用到了encodeURIComponent(query),就用下面这种方式取值;兼容任何编码和浏览器*/
word=java.net.URLDecoder.decode(word);
word = new String(word.getBytes("ISO-8859-1"),"UTF-8");
}
Php:
$word="";
if(!Empty($_POST["word"])){
$word = $_POST["word"].trim();
$word = iconv("utf-8", "gbk",urldecode($word));
}