Как динамически обновить шаблон Flask, когда пользователю нравится сообщение? - PullRequest
0 голосов
/ 13 апреля 2019

У меня есть простая веб-страница на основе блога, где вы можете ставить лайки, но когда like_action происходит, это обновляет всю страницу, и это очень плохо, когда вы уже находитесь внизу страницы.В общем, я просто хочу обновить часть HTML.

Я много читал об ajax, но когда попытался реализовать его, он не очень хорошо работал :(

@posts.route('/like/<int:post_id>/<action>', methods=['GET', 'POST'])
@login_required
def like_action(post_id, action):
    post = Post.query.filter_by(id=post_id).first_or_404()
    if action == 'like':
        current_user.like_post(post)
        db.session.commit()
    if action == 'unlike':
        current_user.unlike_post(post)
        db.session.commit()
    return render_template('section.html', post = post)
<div class="likes" id="result{{post.id}}">
  <hr>
  {% if current_user.is_authenticated %}
    {% if current_user.has_liked_post(post) %}
      <a class="updateButton" post_id="{{post.id}}" href="{{ url_for('posts.like_action', post_id=post.id, action='unlike') }}"><img src="{{url_for('static', filename='heart-filled.png')}}" style="width:5%; height:5%;"></a>
    {% else %}
      <a class="updateButton" post_id="{{post.id}}" href="{{ url_for('posts.like_action', post_id=post.id, action='like') }}"><img src="{{url_for('static', filename='heart-no-fill.png')}}" style="width:5%; height:5%;"></a>
    {% endif %}
  {% else %}
    <img src="{{url_for('static', filename='heart-no-fill.png')}}" style="width:5%; height:5%;">
  {% endif %}
  <small>{{post.likes.count()}}</small>
</div>

      $(document).ready(function(){

        $(document).on('click','.updateButton', function(){

          var post_id = $(this).attr('post_id');

          req = $.ajax({
            url:'/like/<int:post_id>/<action>'
            type:'POST'
            data: {id:post_id}
          });

          req.done(function(data){
            $('result'+post_id).html(data);
          });

        });

Ответы [ 2 ]

1 голос
/ 13 апреля 2019

В вашей функции ajax .done() вы должны изменить это:

$('result'+post_id).html(data)

на эту

$('#result'+post_id).html(data)

, потому что в jQuery вы должны добавить # к первому изваши запросы для id

0 голосов
/ 14 апреля 2019

Это просто моя концепция.Это даст вам представление о том, как вы можете с этим справиться.

Вы можете увидеть, как я прикрепил атрибуты like и like к id, чтобы я мог опубликовать его как ajax

 <a class="unlike" id="unlike_{{post.id}}" href="{{ url_for('posts.like_action', post_id=post.id, action='unlike') }}"><img src="{{url_for('static', filename='heart-filled.png')}}" style="width:5%; height:5%;"></a>


      <a class="like" id="like_{{post.id}}" href="{{ url_for('posts.like_action', post_id=post.id, action='like') }}"><img src="{{url_for('static', filename='heart-no-fill.png')}}" style="width:5%; height:5%;"></a>

Здесь вы можете передать postid как post_id1 и action как like_like

, следовательно, вы можете получить что-то вроде

if likeunlike == 'like':
        current_user.like_post(post)
        db.session.commit()
    if likeunlike == 'unlike':
        current_user.unlike_post(post)

, вот как ваш ajax-скрипт может выглядеть как

$(document).ready(function(){

    // like and unlike click
    $(".like, .unlike").click(function(){
        var id = this.id;   // Getting Button id
        var split_id = id.split("_");

        var text = split_id[0];
        var post_id1 = split_id[1];  // postid



        // AJAX Request
        $.ajax({
            url: '/ur-url',
            type: 'post',
            data: {post_id1:post_id1,likeunlike:text},
            dataType: 'html',
            success: function(data){
                //var likes = data['likes'];
                //var unlikes = data['unlikes'];

                $("#likes_"+post_id).html(data);        // setting likes
                $("#unlikes_"+post_id).html(data);    // setting unlikes


            }

        });

    });

});

Это просто концепция.Время не на тайне, иначе я бы больше вникал внутрь ... Спасибо

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...