使用表单实现目录图1.png所示登录,要求点击登录之后将数据发送到localhost:3000/login接口,并得到登录成功的提示,其中用户名为admin,密码为123456,请求方法为post方法,如果没有填入用户名和密码,则不允许提交,并弹出如图2.png
时间: 2024-03-21 19:40:35 浏览: 11
好的,实现这个功能需要在前端使用表单进行提交,然后使用后端接口进行处理。以下是一个简单的示例代码,以供参考:
HTML代码:
```html
<form id="login-form">
<label for="username">用户名:</label>
<input type="text" id="username" name="username">
<br>
<label for="password">密码:</label>
<input type="password" id="password" name="password">
<br>
<button type="submit">登录</button>
</form>
```
JavaScript代码:
```javascript
const form = document.querySelector('#login-form');
form.addEventListener('submit', (event) => {
event.preventDefault(); // 阻止表单默认提交行为
const username = form.elements.username.value;
const password = form.elements.password.value;
if (!username || !password) {
alert('请填写完整的用户名和密码');
return;
}
const data = new FormData();
data.append('username', username);
data.append('password', password);
fetch('http://localhost:3000/login', {
method: 'POST',
body: data
})
.then(response => response.json())
.then(data => {
if (data.success) {
alert('登录成功');
} else {
alert('登录失败,请检查用户名和密码');
}
})
.catch(error => {
console.error(error);
alert('登录失败,请检查网络连接');
});
});
```
需要注意的是,这段代码中使用了fetch函数进行网络请求,并使用FormData对象来构造表单数据。在fetch函数的then回调函数中,根据接口返回的数据进行相应的处理。如果登录成功,则弹出“登录成功”的提示框,否则弹出“登录失败”的提示框。
另外,为了防止表单默认提交行为,需要在submit事件的回调函数中调用preventDefault函数。如果用户名或密码为空,需要弹出相应的提示框,并退出表单提交流程。