利用asp.net輸出js我們大多數都會直接使用Respone.Write()然后根js格式的代碼,再在頁面調用時我們直接這樣是完全可以實現的,下面我來給大家介紹另一種方法
我是我最初的想法以下是代碼片段:
Respone.Write(“hello Word!”);
但是,當你查看客戶端源碼時,你會發現,輸出的內容呈現在源碼的最前端,顯然它破壞了HTML的格式,在某些情況下這是會影響到頁面布局等效果的。正確的輸出方式應該是:
this.ClientScrthis.ClientScript.RegisterClientScriptBlock也類似UpdatePanel
當你想在UpdatePanel內輸出一段JS時,運用以上方法就會得不到預期的效果。那么請看一下示例。
有一個UpdatePanel的ID是upPn
ScriptManager.RegisterClientScriptBlock(upPn,this.GetType(), "scriptKey", "alert('hello word!');",True)ScriptManager.RegisterStartupScript(upPn,this.GetType(), "scriptKey", "alert('hello word!');",True)這樣的話,當UpdatePanel內容加載到客戶端后,就會彈出“hello word!”對話框。
這樣的話,從后臺輸出JS就更加方便了
還有一種辦法,就是像生成xml一樣直接生成js文件了,這樣直接調用js文件,就可以了,實例
PRotected override void Render(HtmlTextWriter writer){ int titleid =0; StringWriter html = new StringWriter(); System.Web.UI.HtmlTextWriter tw = new System.Web.UI.HtmlTextWriter(html); base.Render(tw); StreamWriter sw; string dir = Server.MapPath("~/js/ask/"); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } string path = dir + "ask"+"_" + titleid + ".js"; sw = new StreamWriter(path, false, System.Text.Encoding.UTF8); string newhtml = html.ToString().Replace(""", "").Replace("rn", ""); string lasthtml = "document.write("" + newhtml + "")"; sw.Write(lasthtml.ToString()); sw.Close(); tw.Close();}JS文件調用亂碼解決方法
1、 問題:后臺字體倒顯示?效果如下:
原因:由于Asp.net采用UTF-8編碼,原先使用GB2312導致亂碼。
解決方法:在Web.config中添加 以下代碼段
<system.web><globalization requestEncoding="utf-8" responseEncoding="utf-8" uiCulture="zh-CN" culture="zh-CN" fileEncoding="utf-8" /></system.web>在解決完后臺亂碼問題,接著出現前臺亂碼問題,詳情問題2
2、 問題:在添加完以上節點后,系統前臺頁面出現以下亂碼問題:
原因:由于添加了 fileEncoding="utf-8"該項目,造成導航無法顯示
解決方法:刪除該選項
3、 問題:由系統后臺生成的JS文件,在前臺的*.aspx的頁面中調用時亂碼,效果如下:
原因:JS采用的是GB2312編碼,而*.aspx采用的UTF-8編碼方式,解決思路,統一編碼方式
解決方法:第一步:根據問題1解決方法操作,注:不要加 fileEncoding="utf-8"
第二步:在需要調用到JS的aspx頁中加入 <meta http-equiv="Content-Type" content="text/html; charset=GB2312" />
第三步:在頁面加載事件中加入下句
protected void Page_Load(object sender, EventArgs e){ Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");}
新聞熱點
疑難解答