客户端与服务器端对URL字符编码和解码的测试

客户端与服务器端对URL字符编码和解码的测试

最近在项目里需要在页面之间通过URL传递商界名人姓名,最初直接传递原始的姓名信息,由于我们使用了AJAX异步请求,最后发现在服务器端处理时很不方便,有时还会有乱码.为了使得通过URL顺利传输特定字符,我们往往需要对待传递的字符进行编码,然后在接收方进行解码.这样做的好处,一是可以解决乱码问题,二是有效保护了我们需要传递的数据资料.以前在一个项目了,为了传递参数的安全,我们曾经采取Session传递变量,这样确实很方便,可是却大大地增加了服务器负担.

关于URL字符编码,可以使用客户端脚本方法escape(string)或者使用服务器端C#方法Server.UrlEncode(string)方法.
下面是进行编码和解码小例子,通过XMLHttpRequest向服务器发送请求:





<script type="text/javascript">
var xmlHttpRequest = null;
var requestPath = "/Handler/Practice.ashx?request=";
function sendRequest(type){
    var tag = (type == 0) ? "geturlencode" : "geturldecode";
    var key = type == 0 ? escape(document.getElementById("keybox").value) : document.getElementById("keybox").value;
    url = requestPath + tag + "&key=" + key;
    xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
    xmlHttpRequest.onreadystatechange = function(){
        if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200){
            document.getElementById("resultdiv").innerHTML = xmlHttpRequest.responseText;
            xmlHttpRequest = null;
        }
    };
    xmlHttpRequest.open("GET", url, true);
    xmlHttpRequest.send();
}
</script>
<input type="text" id="keybox" value="卜" />
<input type="button" value="进行编码" onclick="sendRequest(0);" />
<input type="button" value="进行解码" onclick="sendRequest(1);" />
<br />
<div id="resultdiv"></div>