js前台与后台数据交互-后台调前台(后台调用、注册客户端脚本)

来源:互联网 发布:电力大数据的来源 编辑:程序博客网 时间:2024/04/29 09:34

客户端脚本一般都在前台,这里讲的是(1)在后台调用前台定义的脚本(2)在后台如何注册客户端脚本


用途

  何时使用服务器代码向页中添加客户端脚本:

  u  当客户端脚本的内容依赖于直到运行时才可用的信息时

  u  当您希望客户端脚本在当页已完成加载或当用户提交页时执行


方法


(一)用Response.Write方法写入脚本

  比如在你单击按钮后,先操作数据库,完了后进行弹出框提示Response.Write("<scripttype='text/javascript'>alert();</script>");

  缺陷:这个方法不能调用脚本文件中的自定义的函数,只能调用内部函数,具体调用自定义的函数只能在Response.Write写上函数定义,比如Response.Write("<scripttype='text/javascript'>function myfun(){alert(‘a’)}</script>");

  (注意,后一个response方法与前一个不同,不会立即弹出框,因为它只是注册了一个客户端脚本函数,并不会执行该函数,所以只有调用myfun()函数时才会弹出框)


(二)通过Page 对象的 ClientScript 属性获取对 ClientScriptManager 类的引用以动态注册、调用客户端脚本

  ClientScriptManager类简介:ClientScriptManager 类用于管理客户端脚本并将它们添加到Web 应用程序中,通过键 String 和 Type 唯一地标识脚本。具有相同的键和类型的脚本被视为重复脚本。使用脚本类型有助于避免混淆可能用在页中的来自不同用户控件的相似脚本。


(1)方法ClientScriptManager.RegisterStartupScript(Type type, String key , String  script)

  参数

    type:要注册的启动脚本的类型(一般直接填this.GetType()即可)。

    key:要注册的启动脚本的键(相当于为执行脚本起一个名字,任意名即可)。

    script:要注册的启动脚本文本("<script>函数()</script>",函数()可以为系统函数也可以为前台定义的js函数)。


  Ø  客户端脚本由它的键(key)和类型(type)唯一标识。具有相同的键和类型的脚本被视为重复脚本。

  Ø  调用 IsStartupScriptRegistered 方法以确定具有给定的键和类型对的启动脚本是否已经注册,从而避免不必要的添加脚本尝试。

  Ø  RegisterStartupScript 方法添加的脚本块在页面加载完成但页面的 OnLoad 事件引发之前执行


  举例:

  前台代码:

  

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="RegisterStartupScript.aspx.cs" Inherits="WebApplication4.WebForm12" %><!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>    <title></title>    <script type="text/javascript">        function test() {            alert("前台定义的客户端脚本");        }            </script></head><body>    <form id="form1" runat="server">    </form></body></html>


  后台代码:

  

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;namespace WebApplication4{    public partial class WebForm12 : System.Web.UI.Page    {        protected void Page_Load(object sender, EventArgs e)        {            //从 Page 对象的 ClientScript 属性获取对 ClientScriptManager 类的引用            ClientScriptManager cs = Page.ClientScript;            //方法中直接嵌入脚本,有弊端            Response.Write("<script>alert('方法中直接嵌入脚本');</script>");            //ClientScript直接在后台注册客户端脚本            String csname1 = "PopupScript1";            Type cstype = this.GetType();            //判断startup script是否已被注册            if (!cs.IsStartupScriptRegistered(cstype, csname1))            {                String cstext1 = "alert('后台定义的客户端脚本');";//后台定义客户端脚本                cs.RegisterStartupScript(cstype, csname1, cstext1, true);            }            //ClientScript调用前台定义的客户端脚本            String csname2 = "PopupScript2";            //判断startup script是否已被注册            if (!cs.IsStartupScriptRegistered(cstype, csname1))            {                String cstext2 = "test();";//test()为前台定义的客户端脚本                cs.RegisterStartupScript(cstype, csname2, cstext2, true);            }            //ClientScript.RegisterStartupScript(Type type,string key ,string script)方法            string csname3 = "PopupScript3";            //判断startup script是否已被注册            if (!cs.IsStartupScriptRegistered(cstype, csname1))            {                String cstext3 = "<script>test();</script)";                cs.RegisterStartupScript(cstype, csname3, cstext3);            }        }    }}

  注:重载方法 ClientScript.RegisterStartupScript(Typetype,stringkey, string script,bool flag)

    多了一个参数:addScriptTags

    指示是否添加脚本标记的布尔值,指示 script 参数中提供的脚本是否包装在 <script> 元素块中。将 addScriptTags 设置为 true 指示脚本标记将自动添加。设置为 false,所以脚本开始标记和结束标记包含在 script 参数中。


(2)方法 ClientScriptManager.RegisterClientScriptBlock(Type, String, String)

  参数与重载方法与方法一很类似,不多介绍

  Ø  向页的顶部添加一个脚本块。以字符串形式创建脚本,然后将其传递给方法,方法再将脚本添加到页中。

  Ø  可以使用此方法将任何脚本插入到页中。请注意,脚本可能在所有元素完成之前呈现到页中;因此,您可能无法从脚本中引用页上的所有元素。

  Ø  调用 IsClientScriptBlockRegistered 方法以确定具有给定的键和类型对的客户端脚本是否已经注册,从而避免不必要的添加脚本尝试

  使用方法与方法一也大致相同,直接看实例:


  后台代码(注册客户端脚本):

 

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Text;namespace WebApplication4{    public partial class WebForm13 : System.Web.UI.Page    {        public void Page_Load(Object sender, EventArgs e)        {            // 定义参数变量            String csname1 = "PopupScript";            Type cstype = this.GetType();            // 从 Page 对象的 ClientScript 属性获取对 ClientScriptManager 类的引用            ClientScriptManager cs = Page.ClientScript;            // 判断startup script是否已被注册            if (!cs.IsClientScriptBlockRegistered(cstype, csname1))            {                //运用StringBuilder需要导入using System.Text命名空间                StringBuilder cstext2 = new StringBuilder();                //注册客户端脚本,由前台调用                cstext2.Append("<script type=text/javascript> function DoClick() {");                cstext2.Append("alert('hello')} </");                cstext2.Append("script>");                cs.RegisterClientScriptBlock(cstype, csname1, cstext2.ToString(), false);            }            //调用前台定义的脚本与方法一类似,不做介绍        }    }}


  前台代码:

 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="RegisterClientScriptBlock.aspx.cs" Inherits="WebApplication4.WebForm13" %><!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>    <title>ClientScriptManager Example</title></head>  <body> <form id="Form1"         runat="server">         <%--调用后台注册的客户端脚本--%> <input type="button" value="ClickMe" onclick="DoClick()"/> </form>  </body></html>


(3)方法ClientScriptManager.RegisterClientScriptInclude(Stringkey, String src)

  参数

    key:要注册的客户端脚本包含的键。

    url:要注册的客户端脚本所在的js文件的URL。


  Ø  调用 IsStartupScriptRegistered 方法以确定具有给定的键和类型对的客户端脚本包含是否已经注册

  Ø  与 RegisterClientScriptBlock 方法类似,但此方法将添加引用外部 .js 文件的脚本块。包含文件在任何其他动态添加的脚本之前添加;因此,您可能无法引用页上的某些元素。(重载方法不多说)

  直接看实例:

  testJs.js文件中的代码:

  

function testFun(){    alert("这是独立的js文件中得客户端脚本");}


  后台代码:  

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;namespace WebApplication4{    public partial class RegisterClientScriptInclude : System.Web.UI.Page    {        protected void Page_Load(object sender, EventArgs e)        {                        //定义参数变量            String csname = "ButtonClickScript";            String csurl = "~/testJs.js";            Type cstype = this.GetType();            // 从 Page 对象的 ClientScript 属性获取对 ClientScriptManager 类的引用            ClientScriptManager cs = Page.ClientScript;            // 判断script是否已被注册            if (!cs.IsClientScriptIncludeRegistered(cstype, csname))            {                //在后台注册客户端脚本                cs.RegisterClientScriptInclude(cstype, csname, ResolveClientUrl(csurl));            }           //当然可以用RegisterStartupScript方法直接调用js文件代码,如下            ClientScript.RegisterStartupScript(this.GetType(), "csname2", "testFun()", true);        }    }}


  前台代码:

 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="RegisterClientScriptInclude.aspx.cs" Inherits="WebApplication4.RegisterClientScriptInclude" %><!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>    <title></title>    不必用下面的语句在前台注册testJs.js脚本文件,已在后台注册    <%--<script src="testJs.js" type="text/javascript">            </script>--%></head><body>    <form id="form1" runat="server">      <div>          <%--调用后台注册的testJs.js文件中的脚本--%>        <input type="button" value="ClickMe" onclick="testFun()"/>     </div>    </form></body></html>


(4)方法ClientScriptManager.RegisterOnSubmitStatement(Type type,String key, String script)

  Ø  添加响应页的 onsubmit 事件而执行的脚本。

  Ø  调用 IsOnSubmitStatementRegistered 方法可确定某 OnSubmit 语句是否已通过给定的键/类型对注册,从而避免不必要地添加脚本的尝试。

  Ø  RegisterOnSubmitStatement 方法的 script 参数可以包含多个脚本命令,只要它们以分号 (;) 正确地分隔。

  Ø  RegisterOnSubmitStatement 添加一个脚本,该脚本在页面提交前执行并提供取消提交的机会。

  实例:  

  后台代码:

 

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;namespace WebApplication4{    public partial class RegisterOnSubmitStatement : System.Web.UI.Page    {        public void Page_Load(Object sender, EventArgs e)        {            // 定义参数变量            String csname = "OnSubmitScript";            Type cstype = this.GetType();            // 从 Page 对象的 ClientScript 属性获取对 ClientScriptManager 类的引用            ClientScriptManager cs = Page.ClientScript;            // 判断script是否已被注册            if (!cs.IsOnSubmitStatementRegistered(cstype, csname))            {                String cstext = "document.write('Text from OnSubmit statement');";                cs.RegisterOnSubmitStatement(cstype, csname, cstext);            }        }    }}


  前台代码: 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="RegisterOnSubmitStatement.aspx.cs" Inherits="WebApplication4.RegisterOnSubmitStatement" %><!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>    <title></title></head><body>    <form id="form1" runat="server">        <%--定义sumit按钮,点击提交页面,以触发后台注册的脚本--%>    <input type="submit" value="Submit"/>    </form></body></html>


(三)向 asp.net web服务器控件添加客户端脚本事件

  以编程方式向 ASP.NET 控件添加客户端事件处理程序

    #在页面的 Init 或 Load 事件中调用控件的 Attributes 集合的 Add 方法。 

  向按钮控件添加客户端 Onclick 事件

    #在按钮控件(Button、LinkButton 和 ImageButton 控件)中,将 OnClientClick 属性设置为要执行的客户端脚本

  举例:

  前台代码:

  

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="testServerControls.aspx.cs" Inherits="WebApplication4.testServerControls" %><!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>    <title></title>    <script type="text/javascript">        function test() {            alert("hello new world");        }            </script></head><body>    <form id="form1" runat="server">    <div>        <asp:Button ID="btnServer" runat="server" Text="Button"/>        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>        <span id="spanCounter"></span>    </div>    </form></body></html>

 后台代码:  

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;namespace WebApplication4{    public partial class testServerControls : System.Web.UI.Page    {        protected void Page_Load(object sender, EventArgs e)        {           //将客户端按钮控件的属性设置为客户端脚本test()            btnServer.OnClientClick = "test()";            //调用控件的 Attributes 集合的 Add 方法            String displayControlName = "spanCounter";            //在span中显示文本框的字符长度            TextBox1.Attributes.Add("onkeyup", displayControlName + ".innerText=this.value.length;");                        }    }}


总结

  因为js非常灵活强大,我们往往在后台需要用到它的方法;当客户端脚本的内容依赖于直到运行时才可用的信息时;当您希望客户端脚本在当页已完成加载或当用户提交页时执行;都会用到后台调用或注册客户端脚本的技术。


  以上是总结的后台注册、调用客户端脚本的方法,请参考。。。