JS小技巧 前台JS代碼中獲得後台頁面中的變數的值

來源:互聯網
上載者:User

 

代碼貼出,分享給大家:

後台test.aspx.cs代碼:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;

public partial class test : System.Web.UI.Page
...{

    protected string strJS;//這個變數是要傳遞到前台JS代碼中的,變數聲明的位置一定要在Page類首部,且必須聲明為受保護的:protected
    
    protected void Page_Load(object sender, EventArgs e)
    ...{

    }
    //點擊按鈕事件,在前台動態產生一段JS代碼
    protected void Button1_Click(object sender, EventArgs e)
    ...{
        string[] str =...{"aaa","bbb","ccc"};
        StringBuilder sb = new StringBuilder();
        sb.Append("name='"+str[0]+"' ");
        sb.Append("sex='"+str[1]+"' ");
        sb.Append("age='"+str[2]+"' ");
        strJS = sb.ToString();//給strJS賦值
    }
}

 前台test.aspx代碼:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="test.aspx.cs" Inherits="test" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>無標題頁</title>
    <script>
    var name;
    var sex;
    var age;//這三個變數和後台傳過來的strJS中的變數一致的
    <%=strJS %>//這句是關鍵,相當於response.write(strJS),就是動態產生了一段JS代碼,在你點擊了按鈕後,就會動態產生這段代碼,這段JS代碼是一段指派陳述式,你可以在點擊了按鈕後查看網頁的源檔案
    function print()
    ...{
        alert(name+' '+sex+' '+age);
    }   
    </script>
</head>
<body onload="print()">
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /></div>
    </form>
</body>
</html>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.