为什么我的获取请求被发送多次?
2021-10-27
2099
我正在尝试使网站上的评论成为可能。如果我发布第一条评论,它会正常发布。如果发布第二条评论,fetch 会发送 2 个请求并显示同一条评论 2 次,第三条评论会发送 3 个请求并显示 3 次,等等。我需要做什么才能使一切正常?
js
function insertNewComment(data) {
var ul = document.getElementById("new-comment");
ul.insertAdjacentHTML('afterBegin', '<li class="list-group-item">' + data.text + '</li>');
}
function sendComment() {
document.getElementById('comment').addEventListener('submit', (e) => {
e.preventDefault();
const formData = new FormData(e.target);
fetch(e.target.getAttribute('action'), {
method: e.target.getAttribute('method'),
body: formData
})
.then((response) => {
return response.json();
})
.then((data) => {
insertNewComment(data);
document.getElementById('comment').reset();
});
});
}
html
{% extends 'base.html' %}
{% block other_resources %}
<link rel="stylesheet" href="{{ url_for('.static', filename='css/post.css') }}">
<script src="{{ url_for('.static', filename='js/post.js') }}"></script>
{% endblock %}
{% block content %}
<div class="card">
<img src="{{ post.photo_path }}" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">{{ post.title }}</h5>
<p class="card-text">{{ post.text }}</p>
<p class="card-text"><small class="text-muted">{{ post.created }}</small></p>
<div class="card-header">
Написать комментарий:
</div>
<div>
<form action="{{ url_for('news.add_comment', post_id=post.id) }}" id='comment' method="POST">
{{form.csrf_token}}
<div class="form-floating">
{{form.text(class='form-control')}}
{{form.text.label(for="floatingTextarea2")}}
</div>
{{form.submit(class="btn btn-dark send-comment", onclick='sendComment()')}}
<div class="form-floating">
<label for="floatingTextarea2">Комментарий</label>
</div>
</form>
</div>
<div class="card comments">
<div class="card-header">
Комментарии:
</div>
<ul class="list-group list-group-flush" id='new-comment'>
{% for c in comments %}
<li class="list-group-item">{{ c.text }}</li>
{% endfor %}
</ul>
</div>
</div>
</div>
{% endblock %}
1个回答
每次执行
sendComment
时,都会向该
form
添加另一个
submit
监听器。
确保只添加一个监听器:
function sendComment(e) {
e.preventDefault();
const formData = new FormData(e.target);
fetch(e.target.getAttribute('action'), {
method: e.target.getAttribute('method'),
body: formData
})
.then((response) => {
return response.json();
})
.then((data) => {
insertNewComment(data);
document.getElementById('comment').reset();
});
};
// add the listener outside of `sendComment`
document.getElementById('comment').addEventListener('submit', sendComment);
connexo
2021-10-27