Firefox自动对url中的中文进行编码导致乱码

先看下面一个例子:

index.htm:
<script language="javascript">
title = "木子屋";
document.write("参数值未编码(http://localhost/003.htm?title=木子屋):<br/>");
document.writeln("<iframe width=\"300\" height=\"300\" src=\"http://localhost/002.htm?title="+title+"\" frameborder=1 marginwidth=0 marginheight=0></iframe>");
document.writeln("</p>");
document.write("参数值编码(http://localhost/003.htm?title=%u6728%u5B50%u5C4B):<br/>");
document.writeln("<iframe width=\"300\" height=\"300\" src=\"http://localhost/003.htm?title="+escape(title)+"\" frameborder=1 marginwidth=0 marginheight=0></iframe>");
</script>

002.htm:
<script language="javascript">
//获取查询字符串中的参数值
function GetParam(parmName)
{
    var url    = document.location.search;
    if(url!="undefined")
    {
        var arrParam    = url.split("&");

        for(var i =0;i<arrParam.length;i++)
        {
            var loc    = arrParam[i].indexOf(parmName+"=");

            if(loc!=-1)
            {
                return arrParam[i].replace(parmName+"=","").replace("?","");
                break;
            }
            
        }
    }
}
document.write("title:" + GetParam("title"));
</script>

003.htm:
<script language="javascript">
//获取查询字符串中的参数值
function GetParam(parmName)
{
    var url    = document.location.search;
    if(url!="undefined")
    {
        var arrParam    = url.split("&");

        for(var i =0;i<arrParam.length;i++)
        {
            var loc    = arrParam[i].indexOf(parmName+"=");

            if(loc!=-1)
            {
                return arrParam[i].replace(parmName+"=","").replace("?","");
                break;
            }
            
        }
    }
}
document.write("title(解码):" + unescape(GetParam("title")));
</script>

分别在IE和Firefox打开http://localhost/index.htm可以得到以下结果:

IE:002.htm和003.htm都显示正常;
Firefox:002.htm显示为乱码,003.htm显示正常;


Firefox乱码的原因是由于Firefox对地址中的中文采取了不同于IE的编码方式(网上说法),也就是说:

当url参数值含有中文时必须使用escape进行编码!

测试中还发现,当参数值没有用escape进行编码时,使用unescape进行解码IE下不会乱码,但Firefox下会乱码!


评论: 0 | 引用: 0 | 查看次数: 7952
发表评论
登录后再发表评论!