我在 python Flask 应用程序中为“喜欢”和“不喜欢”按钮实现的 AJAX 遇到了奇怪的问题。以下是 .html 和 .js 文件的代码。
.html
{% for article in articles %}
{% if article._id in likes %}
<button data-toggle="tooltip" title="Unlike" id="unlike-button" value="{{article._id}}"><span id="user-like-recommend" class="glyphicon glyphicon-heart" aria-hidden="true"></span></button>
{% else %}
<button data-toggle="tooltip" title="Like" id="like-button" value="{{article._id}}"><span id="user-like-recommend" class="glyphicon glyphicon-heart-empty" aria-hidden="true"></span></button>
{% endif %}
{% endfor %}
.js
document.getElementById("like-button").addEventListener("click", function(e) {
e.preventDefault();
var article = $('#like-button').val();
var data = {"article": article};
console.log(data);
if(data){
$.ajax({
type: 'POST',
contentType: 'application/json',
url: '/article_liked',
dataType : 'json',
data : JSON.stringify(data),
success: function (response) {
success("Article was successfully liked.");
}
因此,只有第一篇事件文章可以进行 AJAX 调用。
最佳答案
嗯,有多个具有相同 id 的 html 元素,因此所有事件只会针对其中第一个元素触发。
只需在 html 中使用类:
{% for article in articles %}
{% if article._id in likes %}
<button class="unlike-button" ...></button>
{% else %}
<button class="like-button" ...></button>
{% endif %}
{% endfor %}
并在 JavaScript 中使用 jquery 选择器:
$('.like-button').on('click', function(){
var data = { "article": $(this).val()};
... your ajax code
}
关于javascript - 并非所有链接都会触发 AJAX 调用,只有第一个链接会在 Python Flask 应用程序中触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39497363/