简体   繁体   中英

how to serve javascript wtih asp.net page?

I don't know if the title is clear enough or not, but let me explain what I'm trying to do.

I have two webapps with written in asp.net with C#.

App A has the following html.

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

App B receives above request and needs to inject javascript dynamically to the script tag above. I have the following code in App B's page.aspx but it doesn't work. I need App B to return pure javascript, not 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");
         }
     }
}

You might want to use a HttpHandler rather than Page (see http://support.microsoft.com/kb/308001 ) to serve non-HTML content. This would allow you to write something like:

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM