如何用javascript写登录注册
时间: 2023-07-18 20:40:58 浏览: 87
登录注册通常需要与后端进行交互,因此需要使用AJAX或者Fetch等方式将数据提交给后端进行处理。以下是一个简单的使用Javascript和AJAX实现登录注册的示例代码:
1. 登录
HTML代码:
```html
<form id="login-form">
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<br>
<button type="submit">Login</button>
</form>
```
Javascript代码:
```javascript
const loginForm = document.querySelector('#login-form');
loginForm.addEventListener('submit', async (event) => {
event.preventDefault();
const formData = new FormData(loginForm);
try {
const response = await fetch('/api/login', {
method: 'POST',
body: formData
});
if (response.ok) {
// 登录成功
const result = await response.json();
console.log(result);
} else {
// 登录失败
console.error('登录失败');
}
} catch (error) {
console.error(error);
}
});
```
2. 注册
HTML代码:
```html
<form id="register-form">
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<br>
<label for="confirm-password">Confirm Password:</label>
<input type="password" id="confirm-password" name="confirm-password" required>
<br>
<button type="submit">Register</button>
</form>
```
Javascript代码:
```javascript
const registerForm = document.querySelector('#register-form');
registerForm.addEventListener('submit', async (event) => {
event.preventDefault();
const formData = new FormData(registerForm);
const password = formData.get('password');
const confirmPassword = formData.get('confirm-password');
if (password !== confirmPassword) {
console.error('两次输入密码不一致');
return;
}
try {
const response = await fetch('/api/register', {
method: 'POST',
body: formData
});
if (response.ok) {
// 注册成功
const result = await response.json();
console.log(result);
} else {
// 注册失败
console.error('注册失败');
}
} catch (error) {
console.error(error);
}
});
```
以上代码仅供参考,实际情况需要根据后端接口的实现进行相应的修改。
阅读全文