首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET 輸出 JavaScript 的正確方式與編碼問題解決

     編輯:關於ASP.NET

直接使用 Response.Write() 輸出 JavaScript 會導致腳本出現在 HTML 原始碼最前端,破壞文件結構。正確做法是使用 ClientScript 或 ScriptManager 在適當位置註冊腳本。

標準頁面註冊腳本

  • ClientScript.RegisterStartupScript:在 <form> 開始處註冊
  • ClientScript.RegisterClientScriptBlock:在 <form> 結束處註冊
// 基本用法
this.ClientScript.RegisterStartupScript(this.GetType(), "scriptKey", "alert('Hello!');", true);

// 攜帶腳本標籤
this.ClientScript.RegisterStartupScript(this.GetType(), "scriptKey", "<script>alert('Hello!');</script>");

UpdatePanel 非同步回發時的處理

需使用 ScriptManager 對應方法,指定 UpdatePanel 控制項為目標:

ScriptManager.RegisterStartupScript(upPn, this.GetType(), "key", "alert('Hello!');", true);
ScriptManager.RegisterClientScriptBlock(upPn, this.GetType(), "key", "alert('Hello!');", true);

動態產生 .js 檔案的替代方案

重寫 Render 方法,將輸出內容寫入實體 .js 檔,前端直接引用:

protected override void Render(HtmlTextWriter writer) {
    StringWriter html = new StringWriter();
    HtmlTextWriter tw = new HtmlTextWriter(html);
    base.Render(tw);
    
    string dir = Server.MapPath("~/js/ask/");
    if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
    
    string path = dir + "ask_" + titleid + ".js";
    using (StreamWriter sw = new StreamWriter(path, false, Encoding.UTF8)) {
        string newhtml = html.ToString().Replace("\"", "").Replace("\r\n", "");
        sw.Write("document.write(\"" + newhtml + "\")");
    }
    tw.Close();
}

編碼亂碼完整解決方案

問題原因解決方法
後台顯示亂碼ASP.NET 採 UTF-8,原專案為 GB2312Web.config 加入 <globalization requestEncoding="utf-8" responseEncoding="utf-8" culture="zh-CN" uiCulture="zh-CN" />(勿加 fileEncoding)
前台頁面亂碼fileEncoding 導致導航無法顯示移除 fileEncoding 屬性
引用 .js 亂碼.js 為 GB2312,.aspx 為 UTF-81. 統一編碼 2. .aspx 加 <meta charset="GB2312"> 3. Response.ContentEncoding = Encoding.GetEncoding("GB2312")
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved