版权声明:引用请注明来源 https://blog.csdn.net/xfeng20/article/details/86616065
说明
- 本文的主题为:提供一个简单的权限控制,保障后台一定程度的稳定性
- 本文的限制条件:本文做得极端简单,做PC的就不要参考了
先上大家资源
正文
- 原理机制:
sessionStorage()可以设置一个全局变量,该变量在浏览器关闭之前都有效,这样我们就可以通过设置不同的该变量值,来满足我们前端权限的管理了。 - 源码
登陆页面JS验证及sessionStorage()变量赋值
<script type="text/javascript">
function createXHR()
{
var xhr;
try
{
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(E)
{
xhr = false;
}
}
if (!xhr && typeof XMLHttpRequest != 'undefined')
{
xhr = new XMLHttpRequest();
}
return xhr;
}
/*
*异步访问提交处理
*/
function sender()
{
var name = document.getElementById("userName").value;
if (name != "root" && name != "user") {
alert('错误的用户名');
return;
}
var passwd = document.getElementById("userPasswd").value;
console.log(passwd.length);
console.log(isNaN(passwd) )
if(isNaN(passwd) === true)
{
alert("格式错误!请输入数字");
return ;
}
if (passwd.length > 4) {
alert('密码长度不得大于4');
return;
}
else if (passwd.length == 0) {
alert('请输入用户密码');
return;
}
xhr = createXHR();
if(xhr)
{
xhr.onreadystatechange=callbackFunction;
//test.cgi后面跟个cur_time参数是为了防止Ajax页面缓存
xhr.open("GET", "../cgi-bin/rdProcess.cgi?indexPage=" + new Date().getTime());
xhr.send(null);
}
else
{
//XMLHttpRequest对象创建失败
alert("浏览器不支持,请更换浏览器!");
}
}
/*
*异步回调函数处理
*/
function callbackFunction()
{
if (xhr.readyState == 4)
{
if (xhr.status == 200)
{
var returnValue = xhr.responseText.split(',');
if(returnValue != null && returnValue.length > 0)
{
if(document.getElementById("userName").value == "user")
{
if(document.getElementById("userPasswd").value == returnValue[0])
{
sessionStorage["nowName"]="user";
window.open("documents/sysState.html",'_self')
}
else
{
alert("错误的用户密码!");
}
}
else if(document.getElementById("userName").value == "root")
{
if(document.getElementById("userPasswd").value == returnValue[1])
{
sessionStorage["nowName"]="root";
window.open("documents/sysState.html",'_self')
}
else
{
alert("错误的管理员密码!");
}
}
}
else
{
alert("服务器反馈数据异常!");
}
}
else
{
alert("提交失败!");
}
}
}
</script>
其他页面JS权限控制:
<script>
//未登录禁止访问页面,并且弹回到登陆页面
if(sessionStorage["nowName"] != "root" && sessionStorage["nowName"] != "user")
{
alert("请登录");
window.open("../index.html",'_self')
}
//根据不同用户显示不同导航
if(sessionStorage["nowName"] != "root")
{
document.getElementById("adminPara").innerHTML = "";
}
</script>