有時需要在JavaScript中獲取后台變量的值,來判斷JavaScript的執行邏輯,或者需要調用C#后台方法獲取數據,我們可以使用<%= %>表達式很容易地實現,<%= %>主要是對表達式進行綁定,並計算表達式的值。
1.JavaScript獲取后台變量。在后台聲明一個全局變量,並將變量的訪問屬性設置為protected或public,就可以在頁面使用了。
在后台C#代碼中聲明一個protected或public類型的變量:
1 public partial class WebForm1 : System.Web.UI.Page
2 {
3 protected string str;
4 protected void Page_Load(object sender, EventArgs e)
5 {
6 str = "hello";
7 }
8 }<BR>
在前台js中獲取變量的值:
1 <script type="text/javascript">
2 $(document).ready(function () {
3 alert("<%=str %>");
4 });
5 </script>
2.在JavaScript調用后台方法。在后台聲明一個public類型的方法,方法的訪問屬性必須為public,這樣才能在前台訪問。
在后台聲明一個pubic類型的方法:
01 public partial class WebForm1 : System.Web.UI.Page
02 {
03 protected void Page_Load(object sender, EventArgs e)
04 {
05
06 }
07 public string GetStr()
08 {
09 return "hello world";
10 }
11 }
在前台js中調用后台C#方法獲取值:
1 <script type="text/javascript">
2 $(document).ready(function () {
3 alert("<%=GetStr() %>");
4 });
5 </script>