[转载] Ajax中使用Response.Write输出javascript脚本出错的解决办法

转自:http://www.cnblogs.com/firehang/archive/2008/01/21/1047084.html

这一段时间在使用Ajax将老ASP.NET程序升级为Ajax程序,

在升级中发现先前页面中使用Response.Write("<script>alert('数据添加成功!')</script>")的代码执行时出错.

上网上查找解决办法,网上大部分的解决语句是改为 

ScriptManager.RegisterStartupScript(updatePanel1, typeof(UpdatePanel), "aaa", "<script>alert('数据添加成功!')</script>",true);包括陈黎夫著的<<ASP.NET AJAX>>中P104页中解决方法.

     因为我们现在使用Visual Studio 2008 Beta2中的Ajax(3.5),我在使用上述的语句进行处理时,系统并没有预期的脚本运行来跳出对话框,不知是不是Ajax 3.5是不是有改动.

后来经过尝试将ScriptManager.RegisterStartupScript(updatePanel1, typeof(UpdatePanel), "aaa", "<script>alert('数据添加成功!')</script>",true);

中最后的true变为ScriptManager.RegisterStartupScript(updatePanel1, typeof(UpdatePanel), "aaa", "<script>alert('数据添加成功!')</script>",false);

就可以了.下面写一个通用的消息提示类.

 

 1 public class MessageBox
 2 {
 3     
 4     private HttpContext myContext = null;
 5     public MessageBox(HttpContext CurrentContext)
 6     {
 7         myContext = CurrentContext;
 8     }
 9     /// <summary>
10     /// 自定义弹出窗口内容
11     /// </summary>
12     /// <param name="msg"></param>
13     public void Show(string msg)
14     {
15         //myContext.Response.Write("<script>alert('" + msg + "');</script>");
16         ScriptManager.RegisterStartupScript(
        (System.Web.UI.Page)myContext.CurrentHandler,
        typeof(System.Web.UI.Page),
        "aaa", "<script>alert('" + msg + "');</script>", false); 17 } 18 /// <summary> 19 /// 自定义弹出窗口内容并转向一个新的页面 20 /// </summary> 21 /// <param name="msg">自定义消息</param> 22 /// <param name="Url">需要转到的新页面</param> 23 public void Show(string msg,string Url) 24 { 25 //myContext.Response.Write("<script>alert('" + msg + "');javascript:location='"+Url+"';</script>"); 26 ScriptManager.RegisterStartupScript((System.Web.UI.Page)myContext.CurrentHandler, typeof(System.Web.UI.Page), "aaa", "<script>alert('" + msg + "');javascript:location='" + Url + "';</script>", false); 27 28 } 29 /// <summary> 30 /// 自定义弹出窗口内容,自定义是否关闭当前页面 31 /// </summary> 32 /// <param name="msg"></param> 33 /// <param name="close"></param> 34 public void Show(string msg, bool close) 35 { 36 if (close) 37 { 38 // myContext.Response.Write("<script>alert('" + msg + "');javascript:window.close();</script>"); 39 ScriptManager.RegisterStartupScript((System.Web.UI.Page)myContext.CurrentHandler, typeof(System.Web.UI.Page), "aaa", "<script>alert('" + msg + "');javascript:window.close();</script>", false); 40 } 41 else 42 { 43 //myContext.Response.Write("<script>alert('" + msg + "');</script>"); 44 ScriptManager.RegisterStartupScript((System.Web.UI.Page)myContext.CurrentHandler, typeof(System.Web.UI.Page), "aaa", "<script>alert('" + msg + "');javascript:window.close();</script>", false); 45 } 46 } 47 }

 

 

 

使用方法:

1.将MessageBox类放入AppCode文件夹;

2.在Asp.net页面中,要使用后台输出Js对话框的地方:

 

1 MessageBox mb = new MessageBox(this.Context);
2 mb.Show("警告!!!");

 

 

 

 

 

posted @ 2013-02-26 18:38  chutianshu_1981  阅读(198)  评论(0编辑  收藏  举报