I. Description
Sometimes we need to use the value of Session in Javescript.
II. Solution
Session is a variable on the backend server side, while JS is a previous script. There is no ready-made method in JS to get the value of Session, and it needs to be obtained through the server language.
For example, java can be used to get the value of Session and assign it to JS variable.
Take JSP as an example, through:
var id = '<%=session.getAttribute("id")%>';
Note: Java code is enclosed in single quotation marks, and string variables in Java are enclosed in double quotation marks
III. Example
We can make a simple JSP page to display the value of the Session: first set the value of the Session to Imsession, and then display it.
Call the JSP code to run:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<title>Custom browse page</title>
<script type="text/javascript">
function x(){
<%session.setAttribute("id","Imsession");%>
var id = '<%=session.getAttribute("id")%>';
alert("session is "+id);
} </script>
</head>
<body>
<input type ="button" onClick="javascript:x();" value="session">
</body>
</html>