簡體   English   中英

如何獲取JavaScript里面的全局變量和全局function

[英]How to get global variable and global function inside JavaScript

在登錄我的應用程序時,我將登錄詳細信息和令牌詳細信息存儲在 class 的 session 中。現在在我的 aspx 頁面上,我必須寫一個 javascript function,它應該檢查令牌是否在 5 分鍾內過期或分鍾。 如果那么我必須調用 API 以使用刷新令牌更新訪問令牌。 這個API我已經寫在一個全局的class里面了,怎么在JavaScript里面調用這個方法呢? 以及如何獲取存儲在 class 的 session 中的值(例如:login_token_expires_in)在 javascript 中?

`public class GlobalVariables
    {
    public  int login_user_role = 0;
    public  string login_user_name = string.Empty;
    public  string login_user_id = string.Empty;
    public  string login_token = string.Empty;
    public string login_refresh_token = string.Empty;
    public int login_token_expires_in = 0;//1799 sec; 29.9833 minute//1799000
    }
     public class GlobalFunctions
       {
       private bool GetLoginTokenWithRefreshToken(string username, string refresh_token)
        {
           GlobalVariables obj_GlobalVariables =          (GlobalVariables)HttpContext.Current.Session["objGlobalVariableClass"];
           bool status = false;
           string log_data = string.Empty;

           HttpClient client = new HttpClient();
           client.BaseAddress = new Uri(GlobalVariables.WebAPITokenURI);
           HttpResponseMessage response =
           client.PostAsync("e_token",
            new StringContent(string.Format("grant_type=refresh_token&username={0}&refresh_token={1}",
              HttpUtility.UrlEncode(username),
              HttpUtility.UrlEncode(refresh_token)), Encoding.UTF8,
              "application/x-www-form-urlencoded")).Result;
          if (response.IsSuccessStatusCode)
          {
            string resultJSON = response.Content.ReadAsStringAsync().Result;
            e_Token result = JsonConvert.DeserializeObject<e_Token>(resultJSON);
            obj_GlobalVariables.login_token = result.access_token;
            obj_GlobalVariables.login_refresh_token = result.refresh_token;
            obj_GlobalVariables.login_token_expires_in = Convert.ToInt32(result.expires_in * 1000);//seconds to millisec
            status = true;
         }
         else
         {
            status = false;
         }
         return status;
        }
     }`

登錄成功時,將登錄詳細信息存儲在 GlobalVariables class

 `GlobalVariables obj_GlobalVariables = new GlobalVariables();
     obj_GlobalVariables.login_token = result.access_token;
     obj_GlobalVariables.login_token_expires_in = Convert.ToInt32(result.expires_in*1000);//seconds to millisec
    obj_GlobalVariables.login_refresh_token=result.refresh_token;
    obj_GlobalVariables.login_user_name =result.login_user_name;

    etc..`

Page1.aspx 上的 Javascript

  `<script type="text/javascript">
       var idleSecondsTimer = null;
       idleSecondsTimer = window.setInterval(CheckIdleTime, 1000);
       function CheckIdleTime() {
      //have to check if time after login >=  login_token_expires_in - 5 seconds
      //then need to call the function  GetLoginTokenWithRefreshToken(username, refresh_token)
           }
       </script>`

我想知道如何獲取javascript里面的c#全局變量和函數

將登錄詳細信息和令牌詳細信息存儲在 class 的 session 中。

不不不!

您的意思是您創建一個 class 實例,然后將其 SHOVE 到 session() 中進行保存,對嗎? 我在這里的 class 中沒有看到任何“會話” - 所以這必須由您清除。 你這里沒有全局變量。 而且您不能使用 static class,因為它會被所有用戶共享/使用/相同。

一個全局范圍的變量將是 scope 中的 go。所以,你的意思是你創建一個 class 實例,設置值,然后保存到 session() 中,然后你可以檢索它以用於后續的回發。

至於在客戶端使用/擁有/享受這些價值觀?

嗯,你有很多選擇。

您可以創建一個返回值的 web 方法(因此,這將是客戶端 ajax 調用)。

另一種方式?

在某些情況下,我不會進行 web 方法調用,而是將服務器端 class 簡單地推送到頁面上的一個簡單(一個)隱藏字段中。 (你只需將序列化的 class 推入),然后客戶端可以獲取該簡單字符串,將其反序列化為客戶端 object,然后再一次,給定頁面上的 js 客戶端代碼使用所有值那個 class。

這實際上取決於有多少頁,以及您在何處需要 js 代碼中的此類值,但我認為在大多數情況下,web 方法就是通往 go 的方法。

但是,讓我們使用“簡單”隱藏字段,並將 class 發送到客戶端。

所以,說這個簡單的代碼服務器端:

對於此示例,我只是將所有代碼直接推入現有的 web 頁面(因此您甚至可以剪切 + 粘貼並嘗試此操作)。

所以,說這段代碼:

    public class cHotel
    {
        public string FirstName = "";
        public string LastName = "";
        public string HotelName = "";
        public string Description = "";
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            LoadMyData();

        }
    }

    void LoadMyData()
    {
        DataRow drHotel = 
            General.MyRst("SELECT * FROM tblHotelsA WHERE ID = 16").Rows[0];

        cHotel MyHotel = new cHotel();
        MyHotel.FirstName = drHotel["FirstName"].ToString();
        MyHotel.LastName = drHotel["LastName"].ToString();
        MyHotel.HotelName= drHotel["HotelName"].ToString();
        MyHotel.Description = drHotel["Description"].ToString();

        JavaScriptSerializer jsS = new JavaScriptSerializer();

        this.HotelInfo.Value = jsS.Serialize(MyHotel);


    }

客戶端標記是這樣的(我確實有 jQuery,但是那個選擇器可以用 getelementByID 替換 - rest 只是 js 代碼 - 而不是 jQuery。

    <asp:HiddenField ID="HotelInfo" runat="server" ClientIDMode="Static" />

    <div style="padding:40px">

        <asp:Button ID="Button1" runat="server" Text="Button"
            OnClientClick="test1();return false;"
            />


    </div>

    <script>

        function test1() {
            var MyHotel = JSON.parse($('#HotelInfo').val())

            alert("Hotel name = " + MyHotel.HotelName)
            alert("Description = " + MyHotel.Description)


        }

    </script>

因此,當我運行此頁面並單擊按鈕時,我得到/看到了:

在此處輸入圖像描述

所以,上面是將 class 發送到頁面的好方法,它很簡單,不需要花哨的 web 方法或任何東西。

有點不錯,因為該隱藏字段可用於客戶端 js 代碼中的任何和所有例程。 所以,干凈,代碼少,簡單。 隱藏字段將在回發和往返中幸存下來。 因此,簡單、容易、干凈且代碼很少。 並且 hiddenfield 確實有視圖狀態。

然而,現在很多人會建議您使用 web 方法,因此可以從任何 js 代碼調用 web 方法。 但是,您現在正在處理異步調用和更多移動部件。

但是,讓我們在上面發布的 c# 代碼下方添加一個方法,然后試一試,好嗎?

所以,在上面的代碼之后,我們現在有這個:

[WebMethod()]
public static cHotel GetHotel()
{
    DataRow drHotel =
        General.MyRst("SELECT * FROM tblHotelsA WHERE ID = 16").Rows[0];

    cHotel MyHotel = new cHotel();
    MyHotel.FirstName = drHotel["FirstName"].ToString();
    MyHotel.LastName = drHotel["LastName"].ToString();
    MyHotel.HotelName = drHotel["HotelName"].ToString();
    MyHotel.Description = drHotel["Description"].ToString();

    return MyHotel;

}

好的,現在在客戶端,我們將調用上面的 web 方法(ajax 調用)。

所以這:

        function test2() {
            $.ajax({
                type: "POST",
                url: "WebForm1.aspx/GetHotel",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: { },
                success: function (response) {
                    var MyHotel = response.d;
                    alert("Hotel name = " + MyHotel.HotelName)
                    alert("Description = " + MyHotel.Description)
                },
                failure: function (response) {
                    alert(response.d);
                }
            });
        }

同樣,結果是一樣的。 因此,“隱藏字段”技巧或標准 web 方法(這是一個終點)調用都將起作用。

而且我想你可以制作一些“單一”的網絡方法,只返回 class 中的一個值。請記住,雖然 web 方法是“靜態的”(它沒有使用 web 頁面上的控件,但它可以有使用會話())。

所以,這樣說:

    [WebMethod(EnableSession = true)]
    public static cHotel GetHotel()
    {
        DataRow drHotel =
     bla bla bla

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM