Как захватить каждый идентификатор итерации и перейти к jQuery во FLASK - PullRequest
0 голосов
/ 01 июля 2019

Я новичок в jQuery и Flask. Я создаю сайт, похожий на Twitter, с помощью Flask. Когда пользователь входит в систему, он может видеть определенное количество статуса на своей временной шкале. Кроме того, есть 2 кнопки (например, ответить и ретвитнуть), которые они могли бы использовать для взаимодействия с постом. Затем будет запущен jQuery для обработки значения и представления его (ответа) в нижней части статуса в зависимости от того, какая кнопка была нажата. Цикл Flask for используется для вызова и итерации всего состояния из базы данных и представления его в html как единый объект-статус.

Тем не менее, хотя все потоковые состояния могут видеть и кнопки работают. Но процесс jQuery отражается только до первого статуса. Даже когда я пытаюсь захватить status_id и распечатать в console.log (). Он может только захватить первый идентификатор статуса, хотя была нажата последняя кнопка статуса.

Я пытался многими возможными способами, такими как даже сохранить его в значение тега, чтобы к нему можно было получить доступ в javascript. Но это все равно не удалось в конце, где только первый идентификатор статуса может быть захвачен только.

scripts.js

$(document).ready(function() {
    $('#replyform').on('submit', function (event) {
        console.log('i come here');
        $.ajax({
            data: {
                reply: $('#replyInput').val()
            },
            type: 'POST',
            url: $('body').data('replyroute')
        })
            .done(function (data) {
                if (data.error) {
                    $('#rpcommentout').text(data.error).show();
                    console.log('reply failed');

                } else {
                    console.log('reply success');
                    console.log($('body').data('statusid'));
                    console.log($('body').data('statusgroup'));
                    $('#rpcommentout').text(data.result).show();
                    $('#replyform').trigger("reset");
                    $("#replyModalLabel").modal('hide');
                    $('#retweetCommentFeedbackModal').modal('show');
                }
            });
        event.preventDefault();
    });
});

$(document).ready(function(){
    $('#retweetcommentform').on('submit',function(event){
        $.ajax({
            data : {
                retweet: $('#retweetcommentInput').val()
            },
            type: 'POST',
            url: $('body').data('retweetcommentroute')
        })
        .done(function (data){
            if(data.error) {
                $('#rtcommentout').text(data.error).show();
                console.log('retweetcomment failed')
            }
            else {
                console.log('retweetcomment success')
                $('#rtcommentout').text(data.result).show();
                $('#retweetcommentform').trigger("reset");
                $("#retweetCommentModal").modal('hide');
                $('#retweetCommentFeedbackModal').modal('show');
            }
        });
        event.preventDefault();
    });
});

timeline.html

{% block content %}

    <!--access jQuery and script-->
    <script
      src="https://code.jquery.com/jquery-3.4.1.js"
      integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
      crossorigin="anonymous"></script>
    <script type="text/javascript" src="{{ url_for('static',filename='script.js') }}"></script>

    <h1>Your Timeline</h1>
    <!--for normal you may use for post in posts
        if you use pagination, you have to use posts.items-->
    {% for status in data %}
        <article class="media content-section">
            <!--rounded-cricle is bootstrap class; article-img is referring to css we add our own
             the source work like, url_for is for python go static directory, then look for profile_pic file. after that it will concatenate back with author image file-->
          <img class="rounded-circle article-img" src="{{ url_for('static', filename='profile_pic/' + status['image_file'])}}">
          <div class="media-body">
            <div class="article-metadata">
                <h3>{{ status['username'] }}  <small><font color="gray">{{ status['screen_name'] }}</font></small></h3>
              <small class="text-muted">{{ status['created_at'] }}</small>
            </div>
            <!--it will take the id of that particular post and send to post_id in post route-->
            <p class="article-content">{{ status['text'] }}</p>
          <p> status id: {{ status['sta_id'] }}</p>
          <p> index id: {{ index }}</p>
              {% if status['videoid'] != "NA" %}
                  <p>Video Title: {{ status['title'] }}</p>
              {% endif %}
              <p><a href="{{ status['urls_expanded_url'] }}" target="_blank">Click here for more</a></p>
              <p><font size="2">Retweet: {{ status['retweet_count'] }}  Like: {{ status['favorite_count'] }}</font></P>
          <div class="article-metadata2">
              <button type="button" class="btn btn-secondary btn-sm m-1" data-toggle="modal" data-target="#replyModal">Reply</button>
              <button type="button" class="btn btn-secondary btn-sm m-1" data-toggle="modal" data-target="#retweetModal">Retweet</button>
          </div>
              <div>
                  <p><font size="2">Category: {{ status['status_group'] }}</font></P>
                  <p id="rtcommentout"> ... </p>
                  <p id="rpcommentout">...</p>
              </div>
        </div>

        </article>


            <!-- Modal -->
        <div class="modal fade" id="retweetModal" tabindex="-1" role="dialog" aria-labelledby="retweetModalLabel" aria-hidden="true">
          <div class="modal-dialog" role="document">
            <div class="modal-content">
              <div class="modal-header">
                <h5 class="modal-title" id="retweetModalLabel">Retweet?</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                  <span aria-hidden="true">&times;</span>
                </button>
              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Retweet</button>
                  <button type="button" class="btn btn-secondary" data-toggle="modal" data-target="#retweetCommentModal" data-dismiss="modal">Retweet with Comment</button>
              </div>
            </div>
          </div>
        </div>

        <div class="modal fade" id="retweetCommentModal" tabindex="-1" role="dialog" aria-labelledby="retweetCommentModalLabel" aria-hidden="true">
          <div class="modal-dialog" role="document">
            <div class="modal-content">
              <div class="modal-header">
                <h5 class="modal-title" id="retweetCommentModalLabel">Retweet with Comment.</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                  <span aria-hidden="true">&times;</span>
                </button>
              </div>
                <div class="modal-body">
                    <form id="retweetcommentform" name="retweetcommentform">
                        <div class="form-group">
                            <label>Add a comment:</label>
                            <input type="text" class="form-control" name="retweetcommentInput" id="retweetcommentInput" required="1">
{#                            <input type="hidden" value="{{ status['sta_id'] }}" name="sta_id" id="sta_id" />#}
{#                            <input type="hidden" value="{{ status['status_group'] }}" name="status_group" id="status_group"/>#}
                            <body data-statusid="{{ status['sta_id'] }}">
                            <body data-statusgroup="{{ status['status_group'] }}">
{#                            <input type="hidden" value="{{ user }}" name="user_id" />#}
                        </div>
                         <div class="form-group">
                            <button type="submit" id="retweetCommentButton" class="btn btn-secondary">Retweet</button>
                         </div>
                    </form>
                </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>

              </div>
            </div>
          </div>
        </div>

        <div class="modal fade" id="retweetCommentFeedbackModal" tabindex="-1" role="dialog" aria-labelledby="retweetCommentFeedbackModalLabel" aria-hidden="true">
          <div class="modal-dialog" role="document">
            <div class="modal-content">
              <div class="modal-header">
                <h5 class="modal-title" id="retweetCommentFeedbackModalLabel">Retweet with Comment.</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                  <span aria-hidden="true">&times;</span>
                </button>
              </div>
                <div class="modal-body">
                        <div class="form-group">
                            <label>Your tweet was posted.</label>
                        </div>
                </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
              </div>
            </div>
          </div>
        </div>

        <div class="modal fade" id="replyModal" tabindex="-1" role="dialog" aria-labelledby="replyModalLabel" aria-hidden="true">
          <div class="modal-dialog" role="document">
            <div class="modal-content">
              <div class="modal-header">
                <h5 class="modal-title" id="replyModalLabel">Tweet your reply</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                  <span aria-hidden="true">&times;</span>
                </button>
              </div>
                <div class="modal-body">
                    <form id="replyform" name="replyform">
                        <div class="form-group">
                            <label>Add a reply:</label>
                            <input type="text" class="form-control" name="replyInput" id="replyInput" required="1">
                        </div>
                        <div class="form-group">
                            <button type="submit" id="replyButton" name="replyButton" class="btn btn-secondary">Reply</button>
                        </div>
                    </form>
                </div>
              <div class="modal-footer">
                  <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>

              </div>
            </div>
          </div>
        </div>

{% endfor %}
    <a class="btn btn-secondary btn-sm mt-1 mb-1" href="#">Click Here For More Tweet</a>
    <body data-retweetcommentroute="{{ url_for('user.timeline_retweetcomment') }}">
    <body data-replyroute="{{ url_for('user.timeline_reply') }}">
{% endblock content %}

route.py

@user.route("/timeline") # about page
def timeline():
    username = session['username']
    cur = db.connection.cursor()
    sql = "SELECT * FROM user WHERE username LIKE %s"
    cur.execute(sql, [username])
    user = cur.fetchone()
    cur.close()
    cur = db.connection.cursor()
    sql = '''SELECT u.*, s.* FROM user as u inner join status as s on u.user_id = s.user_id order by rand() limit 40'''
    cur.execute(sql)
    pwd = list(cur.fetchall())
    cur.close()
    return render_template('timeline.html', title='Welcome Back - Timeline', data=pwd, user=user['user_id'])


@user.route("/timeline_retweetcomment", methods=['POST'])
def timeline_retweetcomment():
    retweet = request.form['retweet']
    if retweet:
        newRetweet = retweet
        return jsonify({'result': newRetweet})
    return jsonify({'error': 'Missing Data'})


@user.route("/timeline_reply", methods=['POST'])
def timeline_reply():
    reply = request.form['reply']
    if reply:
        newReply = reply
        return jsonify({'result': newReply})
    return jsonify({'error': 'Missing Data'})

Мой результат. Я надеюсь, что идентификатор каждого статуса может быть записан и отправлен в javascript, чтобы я мог захватить взаимодействие с пользователем в другой базе данных. Но проблема, с которой я столкнулся сейчас, состоит в том, чтобы захватить только первый статус взаимодействия. Оставшееся состояние взаимодействия невозможно зафиксировать. Надеюсь, вы, парень, можете помочь в этом. Спасибо

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