微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何用asp.net页面提供javascript?

我不知道标题是否足够清晰,但让我解释一下我要做的事情.

我有两个用asp.net和C#编写的webapps.

App A具有以下html.

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

应用B接收上述请求,需要动态地将javascript注入上面的脚本标记.我在App B的page.aspx中有以下代码,但它不起作用.我需要App 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");
         }
     }
}

解决方法

您可能希望使用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);
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐