DIV CSS 佈局教程網

JS 的 escape 與 C# 的解碼函數 UrlDecode 對應關係
編輯:JavaScript基礎知識     

前端用 JavaScript 的 escape 編碼後,後端在 C# 中可用 System.Web.HttpUtility.UrlDecode(s) 來解碼(注意編碼方式要一致)。使用時需留意以下幾點。

UrlEncode / UrlDecode 的靜態與實例之分

1. HttpUtility.UrlEncode、HttpUtility.UrlDecode 是靜態方法,而 Server.UrlEncode、Server.UrlDecode 是實例方法。
2. Server 是 HttpServerUtility 類的實例,是 System.Web.UI.Page 的屬性。

3. 用兩者編碼的結果並不相同。例如:

string url="https://search.99read.com/index.aspx?book_search=all&main_str=奧迷爾";
Response.Write(HttpUtility.UrlEncode(url));
Response.Write("<br>");
Response.Write(Server.UrlEncode(url));

輸出結果:

http%3a%2f%2fsearch.99read.com%2findex.aspx%3fbook_search%3dall%26main_str%3d%e5%a5%a5%e8%bf%b7%e5%b0%94
http%3a%2f%2fsearch.99read.com%2findex.aspx%3fbook_search%3dall%26main_str%3d%b0%c2%c3%d4%b6%fb

原因:Server.UrlEncode 按本地程序設置的編碼方式編碼,而 HttpUtility.UrlEncode 默認按 .NET 的 UTF-8 編碼。若讓兩者編碼方式一致,結果就相同了:

string url1="https://search.99read.com/index.aspx?book_search=all&main_str=奧迷爾";
Response.Write(HttpUtility.UrlEncode(url1,System.Text.Encoding.GetEncoding("GB2312")));
Response.Write("<br>");
Response.Write(Server.UrlEncode(url1));

按指定編碼獲取 QueryString

有時其他系統傳來的 URL 用的是別的編碼。下面這個自定義方法可獲取指定編碼格式的 QueryString:

public string GetNonNullQueryString(string key,Encoding encoding)
{
// 引用 System.Collections.Specialized 和 System.Text 命名空間
System.Collections.Specialized.NameValueCollection encodingQueryString;
// 該方法在 2.0 中新增
encodingQueryString = HttpUtility.ParseQueryString(Request.Url.Query,encoding);
return encodingQueryString[key] != null ? encodingQueryString[key].Trim() : "";
}

調用:

string url = GetNonNullQueryString("url",Encoding.UTF8).Trim();

escape、encodeURI、encodeURIComponent 的區別

JS 對文本編碼涉及三個函數:escape、encodeURI、encodeURIComponent,對應的解碼函數分別是 unescape、decodeURI、decodeURIComponent。

1. 傳遞參數時用 encodeURIComponent,這樣組合的 URL 才不會被 # 等特殊字符截斷。例如:

document.write('<a href="https://passport.baidu.com/?logout&aid=7&u='
+ encodeURIComponent("https://cang.baidu.com/bruce42") + '">退出</a>');

2. 整體 URL 跳轉時可用 encodeURI。例如:

Location.href=encodeURI("https://cang.baidu.com/do/s?word=百度&ct=21");

3. 處理數據時可用 escape,例如保存 history 記錄。

4. escape 對 0-255 以外的 Unicode 值會輸出 %u**** 格式,其他情況下三者結果相同。

實際中最常用的是 encodeURIComponent,它把中文等字符轉為 UTF-8 的 URL 編碼,因此後端接收時需相應地按 UTF-8 解碼。三者不編碼的字符集也不同:escape 不編碼 69 個字符,encodeURI 不編碼 82 個,encodeURIComponent 不編碼 71 個。總的原則是:編碼單個參數用 encodeURIComponent,編碼整條 URL 用 encodeURI。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved