使用html表单实现登录界面:包括用户名,密码,登录和重新输入按钮。用户名和密码是文本框形式填写;要求点击登录之后将数据发送到localhost:3000/login接口,并得到登录成功的提示,其中用户名为admin,密码为123456,请求方法为post方法,如果没有填入用户名和密码,则不允许提交,并弹出“请填写此字段”的提示
时间: 2024-03-21 19:42:00 浏览: 60
好的,以下是实现登录界面的HTML代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<form id="login-form">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>
<input type="submit" value="Login">
<input type="reset" value="Reset">
</form>
<script>
const loginForm = document.getElementById('login-form');
loginForm.addEventListener('submit', (event) => {
event.preventDefault();
const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
if (!username || !password) {
alert('Please fill in all fields!');
return;
}
if (username === 'admin' && password === '123456') {
fetch('http://localhost:3000/login', {
method: 'POST'
})
.then(response => response.text())
.then(data => alert(data))
.catch(error => console.error(error));
} else {
alert('Incorrect username or password!');
}
});
</script>
</body>
</html>
```
解释一下代码:
1. 我们首先创建了一个表单,里面包含了用户名和密码的文本框,以及登录和重新输入按钮。
2. 我们给表单添加了一个 ID 为 “login-form” 的属性,方便在 JavaScript 中进行操作。
3. 我们使用了 JavaScript 来监听表单的提交事件,当用户点击登录按钮时,我们将阻止表单的默认提交行为。
4. 我们获取用户名和密码文本框的值,并进行了非空校验,如果没有填写则弹出提示信息。
5. 如果用户名和密码正确,则使用 fetch API 发送一个 POST 请求到 localhost:3000/login 接口,并在接口返回成功时弹出提示信息。
6. 如果用户名和密码不正确,则弹出提示信息。
注意:以上代码仅供参考,并不能直接在浏览器中运行,需要在一个服务器环境下运行,例如使用 Node.js 的 express 模块搭建一个简单的服务器。