写一段代码实现分角色登录
时间: 2024-03-14 13:44:02 浏览: 13
以下是一个基于前端实现的分角色登录的示例代码:
HTML:
```html
<form id="login-form">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<label for="role">Role:</label>
<select id="role" name="role">
<option value="admin">Admin</option>
<option value="user">User</option>
</select>
<button type="submit">Login</button>
</form>
```
JS:
```javascript
const loginForm = document.getElementById('login-form');
loginForm.addEventListener('submit', (e) => {
e.preventDefault();
const username = loginForm.elements.username.value;
const password = loginForm.elements.password.value;
const role = loginForm.elements.role.value;
// 发送登录请求到后端,验证用户名密码是否正确
// 如果正确,将角色信息存储到浏览器的本地存储中
localStorage.setItem('role', role);
// 根据角色信息跳转到对应的页面
if (role === 'admin') {
window.location.href = '/admin.html';
} else if (role === 'user') {
window.location.href = '/user.html';
}
});
```
在这段代码中,我们为登录表单添加了一个下拉菜单,让用户选择自己的角色类型。当用户提交表单时,我们获取表单中的用户名、密码和角色类型,并将角色类型存储到浏览器的本地存储中。然后,根据不同的角色类型,跳转到不同的页面。在后续的页面中,我们可以根据浏览器的本地存储中存储的角色信息,来控制用户看到的页面和功能。