動態輸出 JavaScript 時常用 Response.Write(""),但易忽略格式問題導致腳本錯誤。
資料庫連線失敗時捕獲例外訊息輸出 alert,例外訊息包含換行符:
"無法打開登錄 'test' 中請求的資料庫。登錄失敗。
用戶 'sa' 登錄失敗。"
直接輸出產生的 JavaScript:
<script>alert('連接失敗!!出錯原因:無法打開登錄 'test' 中請求的資料庫。登錄失敗。
用戶 'sa' 登錄失敗。');</script>
問題:alert 字串跨行、單引號未轉義,導致「確實 ')'」腳本錯誤。JavaScript 字串不支援跨行,也不支援 C# @ 逐字字串語法。
\n 或空白\'HttpUtility.JavaScriptStringEncode (.NET 4.0+) 完整編碼protected void btnConnect_Click(object sender, EventArgs e)
{
try
{
// 連線資料庫代碼
}
catch (Exception ex)
{
string msg = ex.Message.Replace("\r\n", "\\n").Replace("'", "\\'");
Response.Write(string.Format("<script>alert('{0}');</script>", msg));
}
}
public static string Alert(string msg)
{
return string.Format("<script>alert('{0}');</script>",
msg.Replace("\r\n", "\\n").Replace("'", "\\'"));
}
正確處理換行與引號轉義,即可避免動態輸出 JavaScript 的語法錯誤。