How can I make a session value available to JavaScript?

When my page loads, it stores the identifier from the database in the session: Session["AppId"] = 1234 . However, when I do JavaScript, I need to know what AppId is for database calls. How can I make this available to my JS from server code? Will the script tag be logged with var appId = 1234 , or will this code dry out a bit?

Would adding a custom attribute to the body tag make more sense? data-appid=1234 for example?

I am new to web content, so do it and it’s not always obvious to me. If there is a right / best way, feel free to share it.

EDIT:

I really needed a solution HttpContext.Current.Session["AppId"] . I did not think that static methods could access session values, so I thought that I needed to save them in a method in order to go to my WebMethod through an Ajax call. I accepted the answer I made because he answered the question I asked. I just asked the wrong question. =) I'm new, I remember - come on me!

+4
source share
3 answers

There are many ways to do this:

  • As you wrote, attribute data-*
  • Hidden form field (if you have a form on the page)
  • Paste in URL
  • Exit in javascript to a variable

There is no better opinion of what is best.

+4
source

You can create a hidden field or use a global variable.

Hidden field:

 <input type="hidden" value='<%= Session["AppId"] %>'></input> 

Global variable:

 <script type="text/javascript"> window.AppId = '<%= Session["AppId"] %>'; </script> 
+4
source

I personally output the session value to a global variable as follows:

 <script type="text/javascript"> <?php if(isset($_SESSION["AppId"])) { echo "var AppId=".$_SESSION["AppId"].";"; } else { echo "var AppId=null;"; } ?> </script> 

As an alternative...

While I’m not sure how the application of your client application works, could you check the server side of the AppID value when actually creating the database query?

Thus, the AppID value is never displayed to the user, and they will not be able to use the value through javascript.

0
source

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


All Articles