并非所有链接都触发AJAX调用,只有第一个链接在Python Flask Application中

时间:2016-09-14 18:33:21

标签: javascript jquery python ajax

我在AJAX中遇到了奇怪的问题,我已经为'喜欢'和'不像' python烧瓶应用程序中的按钮。下面是.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调用。

1 个答案:

答案 0 :(得分:1)

嗯,有多个html元素具有相同的id,因此所有事件只会针对其中的第一个触发。

只需使用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
}