[随记]web开发需要注意请求参数编码问题

GET,POST请求数据传递问题

对于GET方式

最好在数据传递之前对数据进行URLEncode 采用服务器默认的编码进行编码

对于POST方式

表单中的参数值对是通过request body发送给服务器。1)浏览器会根据网
页的ContentType(“text/html; charset=GBK”)中指定的编码进行对表单中的数据进行编码,
2)在服务器端的程序中我们可以通过Request.setCharacterEncoding() 设置编码,
3)通过request.getParameter获得正确的数据。

【注】
path部分Firefox、chrome、IE都是采用UTF-8编码格式
对于Query String部分Firefox、chrome采用UTF-8,IE采用GBK
服务器在进行解码过程中URIEncoding就起到作用了

javaScript中全局函数

    encodeURI   //只是对QueryString中的中文进行编码
    encodeURIComponent  //其中的/也会被编码

如:

    原始请求路径:http://www.baidu.com?name=中国
    使用JavaScript:encodeURI方法后结果:http://www.baidu.com?name=%E4%B8%AD%E5%9B%BD
    使用JavaScript:encodeURIComponent方法后结果:http%3A%2F%2Fwww.baidu.com%3Fname%3D%E4%B8%AD%E5%9B%BD

测试源码

<!DOCTYPE html>
<html>
<head>
    <title>js请求路径编码解码</title>
</head>
<body>
<div id="url"></div>
<div id="encodeURI"></div>
<div id="encodeURIComponent"></div>
<div id="escape"></div>
<button onclick="bianMa()">对页面的超链接进行编码</button>
<a href="http://www.bbb.com?name=张三">bbbbbb</a>
<a href="http://www.ccc.com?name=李四">cccccc</a>
<a href="http://www.ddd.com?name=王五">dddddd</a>
<script type="text/javascript">
    var urlBefore = "http://www.baidu.com?name=中国";
    // alert(urlBefore);
    var urlAfter = encodeURI(urlBefore);
    // alert(urlAfter);
    var urlAfter2 = encodeURIComponent(urlBefore);
    // alert(urlAfter2);
    var escapeUrl = escape(urlBefore);
    document.getElementById("url").innerHTML = "原始请求路径:"+urlBefore;
    document.getElementById("encodeURI").innerHTML = "使用JavaScript:encodeURI方法后结果:"+urlAfter;
    document.getElementById("encodeURIComponent").innerHTML = "使用JavaScript:encodeURIComponent方法后结果:"+urlAfter2;
    document.getElementById("escape").innerHTML = "使用JavaScript:escape方法后结果:"+escapeUrl;

    function bianMa(){
        var as = document.getElementsByTagName("a");
        // alert(as.length);
        for(var i=0;i<as.length;i++)
        {
            as[i].href = encodeURI(as[i].href);
        }
    }
    //对所有的链接请求进行编码处理
    var as = document.getElementsByTagName("a");
    // alert(as.length);
    for(var i=0;i<as.length;i++)
    {
        as[i].href = encodeURI(as[i].href);
    }
</script>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值