AJAX下不能使用RESPONSE.WRITE 脚本的解决方案

来源:互联网 发布:威廉古堡 知乎 编辑:程序博客网 时间:2024/05/06 20:11
 

在使用ASP.NET AJAX 开发程序时候 我们以往经常使用 response.write();不能使用。

使用ScriptManager来实现JS注册即可

以前以下代码现在不能在AJAX环境下正确运行

    protected void Button1_Click(object sender, EventArgs e)
    
{
        Response.Write(
"<script>window.open("http://www.baidu.com/");</script>");
  
    }

我们修改以上代码 让他在AJAX下运行起来

  这里的ScriptManager.RegisterStartupScript()为静态方法,注册客户端脚本。第一个参数UpdatePanel1 为JS要输出到的UpdatePanel,opennewwindow 脚本关键字

    protected void Button1_Click(object sender, EventArgs e)
    
{
        
//Response.Write("<script>window.open("http://www.baidu.com/");</script>");
        ScriptManager.RegisterStartupScript(UpdatePanel1, typeof(UpdatePanel), "opennewwindow""window.open("http://www.baidu.com/");"true);
    }

前台ASPX代码

    <form id="form1" runat="server">
    
<div>
        
<asp:ScriptManager id="ScriptManager1" runat="server">
        
</asp:ScriptManager>
    
    
</div>
        
<asp:UpdatePanel id="UpdatePanel1" runat="server">
            
<contenttemplate>
<asp:Button id="Button1" runat="server" Text="Button"  OnClick="Button1_Click"></asp:Button>
</contenttemplate>
        
</asp:UpdatePanel>
        
&nbsp; &nbsp;
    
</form>