JavaScript可以操作session吗
session作为一种较为安全的会话控制,一般来讲是不允许前端来获取的,那么如果我们就是想要通过前端来获取的话有没有办法呢,办法还是有的,笔者这里通过JavaScript发起http请求的方式来设置和获取session(需要借助后端的帮助)
JavaScript设置session的步骤
JavaScript获取session值的步骤
使用案例
- 通过setSession按钮来设置session
- 通过getSession按钮来获取session
效果如下所示:
前端
<!DOCTYPE html>
<html>
<head>
<title>Javascript-Session</title>
</head>
<body>
<label for="user">user</label>
<input type="text" name="user" id="user">
<label for="age">age</label>
<input type="number" name="age" id="age">
<button id="setSession">setSession</button>
<button id="getSession">getSession</button>
<script>
document.getElementById("setSession").addEventListener("click",function(){
var user=document.getElementById("user").value;
var age=document.getElementById("age").value;
var xhr=new XMLHttpRequest();
xhr.open("GET","./setsession.php?user="+user+"&age="+age);
xhr.send();
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status==200){
// 将json字符串转化为JavaScript对象
var response=JSON.parse(xhr.responseText);
// 将session_id和session_name保存到sessionStorage里
sessionStorage.setItem("session_name",response.result.session_name);
sessionStorage.setItem("session_id",response.result.session_id);
alert(xhr.responseText);
}
}
}
})
document.getElementById("getSession").addEventListener("click",function(){
// 从sessionStorage获取session_id,将session_id通过URL传到后端
var session_id=sessionStorage.getItem("session_id");
var xhr=new XMLHttpRequest();
xhr.open("GET","./getsession.php?session_id="+session_id);
xhr.send();
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status==200){
alert(xhr.responseText);
}
}
}
})
</script>
</body>
</html>
后端
设置session
<?php
session_start();
$session_id=session_id();
$session_name=session_name();
$user=$_GET['user'];
$age=$_GET['age'];
$_SESSION['user']=$user;
$_SESSION['age']=$age;
$data=[
"msg"=>"OK",
"code"=>"2000",
"result"=>[
"session_id"=>$session_id,
"session_name"=>$session_name
]
];
$data=json_encode($data);
echo $data;
?>
获取session
<?php
$session_id=$_GET['session_id'];
session_id($session_id);
session_start();
$user=$_SESSION['user'];
$age=$_SESSION['age'];
$data=[
"msg"=>"OK",
"code"=>"2000",
"result"=>[
"user"=>$user,
"age"=>$age
]
];
$data=json_encode($data);
echo $data;
?>