2011-07-27 55 views
4

我不知道標題是否足夠清晰,但讓我解釋我正在嘗試做什麼。如何爲asp.net頁面提供javascript?

我有兩個用C#寫在asp.net中的webapps。

應用程序A具有以下html。

<script type="text/javascript" id="blah" src="http://somServer/AppB/page.aspx?p=q"></script> 

應用程序B收到上面的請求,並需要動態注入JavaScript到上面的腳本標記。我在App B的page.aspx中有以下代碼,但它不起作用。我需要應用程序B返回純JavaScript,而不是HTML。

namespace AppB 
{ 
    public partial class Default : System.Web.UI.Page 
    { 
     if(!Page.IsPostBack) 
     { 
     Response.Clear(); 
     Response.ClearContent(); 
     REsponse.ClearHeader(); 
     Response.AddHeader("content-type", "text/javascript"); 
     var p = Request.Query["p"]; 
     if(!string.IsNullOrEmpty(p)) 
     { 
      this.Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "test", "alert('test');", false"); 
     } 
    } 
} 
+0

你得到什麼樣的錯誤? – Infotekka

+1

你爲什麼要打另一個.aspx頁面?這是一個特定的要求嗎? – TheGeekYouNeed

+0

當你說不起作用...資源是否加載但內容類型不正確?你可以附上FireBug的請求/響應頭文件嗎? – madcapnmckay

回答

3

你可能想使用一個HttpHandler而不是Page(見http://support.microsoft.com/kb/308001)擔任非HTML內容。這將允許你寫這樣的東西:

public class JavascriptHandler : IHttpHandler 
{ 
    public void ProcessRequest(HttpContext context) 
    { 
     context.Response.ContentType = "text/javascript"; 
     string p = context.Request.QueryString["p"]; 
     string script = String.Format("alert('test - p={0}');", p); 
     context.Response.Write(script); 
    } 
} 
+0

有沒有一種方法實現這與Web應用程序項目而不是類庫項目?我的猜測可能是NO,因爲Page類可能已經下了管道。 –

+1

@我自己,答案是肯定的。我可以添加一個通用處理程序(ashx)頁面。 –

相關問題