How to read session values ​​using jQuery

I am using C # and jQuery.

I have the code below where I set the session variable using C # code.

if (!string.IsNullOrEmpty(results))
{
    string[] array = results.Split(',');
    string firstName = array[0];
    string lastName = array[1];
    string activeCardNo = array[2];
    string memberShipTier = array[3];
    string accessToken = array[4];

    Session["skyFirstName"] = firstName.ToString();
    Session["skyLastName"] = lastName.ToString();
    Session["skyActiveCardNo"] = activeCardNo.ToString();
    Session["skyMemberShipTier"] = memberShipTier.ToString();
    Session["boolSignOn"] = "true";
    Response.Redirect(fromPage);
    Response.End();
}

Now I want to read these values ​​( Session["skyFirstName"]) using jQuery so that I can set in my elements. Please suggest.

+3
source share
4 answers

, javascript . script , , jQuery AJAX . , , , . , script .

:

public class ReadSession : IHttpHandler, IReadOnlySessionState
{
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "application/json";
        context.Response.Write(new JavaScriptSerializer().Serialize(new
        {
            Key = context.Request["key"],
            Value = context.Session[context.Request["key"]]
        }));
    }

    public bool IsReusable 
    { 
        get { return true; } 
    }
}

:

$.getJSON('/ReadSession.ashx', { key: 'skyFirstName' }, function(result) {
    alert(result.Value);
});
+6

jquery , . -, -, JSON (,) .

+1

javascript, , .

, , - ajax, javascript . , , , , .

, javascript script, javascript.

+1

jQuery is javascript, so in order to have these variables you need to print the html code (at least one script tag) where you set the reading session variables from C # as a javascript variable.

An alternative could be to use an ajax request to get session variables from a script server.

0
source

Source: https://habr.com/ru/post/1785157/


All Articles