<input type="text" name="name">
<input type="number" name="age">
<input type="text" name="email">
<input type="text" name="name">
<input type="number" name="age">
<input type="text" name="email">
<input type="text" name="name">
<input type="number" name="age">
<input type="text" name="email">
!-- ... n개의 input --!
<button id="submit">등록</button>
input개수는 가변가능성이 있다면 다음과 같이 반복문을 사용하여 request 배열을 만들 수 있다,
const submitButton = document.querySelector('#submit');
submitButton.addEventListener('click', () => {
const users = [];
const inputs = document.querySelectorAll('input[name="name"], input[name="age"], input[name="email"]');
for (let i = 0; i < inputs.length; i += 3) {
const name = inputs[i].value;
const age = inputs[i + 1].value;
const email = inputs[i + 2].value;
const user = { "name":name, "age":age, "email":email };
users.push(user);
}
fetch('/api/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(users)
})
.then(response => {
// 등록이 성공하면 처리합니다.
})
.catch(error => {
// 등록이 실패하면 처리합니다.
});
});
해당요청을 받기 위해서는 서버 컨트롤러에서도 List형태여야한다.
@PostMapping("/api/users")
public ResponseEntity<Void> createUsers(@RequestBody List<User> users) {
userService.createUsers(users);
return ResponseEntity.status(HttpStatus.CREATED).build();
}
해당 방법은 코드가 복잡해질 수 있다. 이 방법은 비교적 간단한 작업에 적합하지만, 대량의 요청을 처리해야하는 경우에는 효율적이지 않다.
시간이 된다면 나중에 내용을 추가할 예정이다.