例如地址:http://localhost:14243/default.aspx?a=申请单 ,第一次访问后 地址没有改变。
但页面postback后,随便点击一个有postback的服务器控件之后
地址会转变成 http://localhost:14243/Default.aspx?a=%u7533%u8bf7%u5355 这个querystring一段是用的unicode的编码方式。
这样的方式直接导致的是 在页面中用 js函数 decodeURIComponent 解码时 出错
QueryString在.net中是HttpValueCollection类型,该函数的tostring方法如下
internal virtual string ToString(bool urlencoded, IDictionary excludeKeys) { int count = this.Count; if (count == 0) { return string.Empty; } StringBuilder builder = new StringBuilder(); bool flag = (excludeKeys != null) && (excludeKeys["__VIEWSTATE"] != null); for (int i = 0; i < count; i++) { string key = this.GetKey(i); if (((!flag || (key == null)) || !key.StartsWith("__VIEWSTATE", StringComparison.Ordinal)) && (((excludeKeys == null) || (key == null)) || (excludeKeys[key] == null))) { string str3; if (urlencoded) { key = HttpUtility.UrlEncodeUnicode(key); } string str2 = (key != null) ? (key + "=") : string.Empty; ArrayList list = (ArrayList) base.BaseGet(i); int num3 = (list != null) ? list.Count : 0; if (builder.Length > 0) { builder.Append('&'); } if (num3 == 1) { builder.Append(str2); str3 = (string) list[0]; if (urlencoded) { str3 = HttpUtility.UrlEncodeUnicode(str3); } builder.Append(str3); } else if (num3 == 0) { builder.Append(str2); } else { for (int j = 0; j < num3; j++) { if (j > 0) { builder.Append('&'); } builder.Append(str2); str3 = (string) list[j]; if (urlencoded) { str3 = HttpUtility.UrlEncodeUnicode(str3); } builder.Append(str3); } } } } return builder.ToString(); }
奇妙的是 Request.Url.AbsoluteUri.ToString(); 显示的querystring那一段用的是utf-8的编码:
"http://localhost:14243/default.aspx?a=%E7%94%B3%E8%AF%B7%E5%8D%95"
真不懂为啥浏览器的地址被篡改成unicode编码,如果是utf-8的方式,js decodeURIComponent 解码就会正确了。
我们可以很容易的发现用的是unicode编码。请问一旦有中文值的querystring,在js端获取要如何正确解码?
unescape("%u7533%u8bf7%u5355")
试验了一下,是可行的。谢谢。