“Jinja内部的Javascript”;至于;环

“Jinja内部的Javascript”;至于;环,javascript,python,flask,Javascript,Python,Flask,我正在用Python Flask编写一个应用程序,我正在用Javascript构建交互式按钮 这是我的路线: @app.route('/jquery') def jquery(): posts = Post.query.all() return render_template('jquery.html', posts=posts) 在jquery.html模板中,我有: {% for p in posts %} {% if p.upvotes %} {% set pupvote

我正在用Python Flask编写一个应用程序,我正在用Javascript构建交互式按钮

这是我的路线:

@app.route('/jquery')
def jquery():
    posts = Post.query.all()
    return render_template('jquery.html', posts=posts)
在jquery.html模板中,我有:

{% for p in posts %}
{% if p.upvotes %}
{% set pupvotes = p.upvotes %}
{% else %}
{% set pupvotes = 0 %}
{% endif %}

<p>{{ p.author.username }} says: <b>{{ p.body }}</b>&nbsp;&nbsp;<button id=" 
{{ p.id }}" onclick="document.getElementById('{{ p.id }}').innerHTML = {{ 
pupvotes }} +1  + ' Likes'">{{ pupvotes }} Likes</button></p>

{% endfor %}

但是无论我点击哪个Like按钮,页面上只有最后一个Like会随着click更新

不过,正如@MartijnPieters所指出的,您已经接近了,您仍然需要与后端进行通信,以更新该帖子的赞数。要做到这一点,请稍微更改HTML以包含一个按钮,用类和id更新喜欢的内容。id将与post id相同,并且类将是泛型的。然后,在创建
脚本之后,使用
jquery
ajax

首先,在Python后端中,创建一个路由来处理帖子类的更新:

@app.route('/update_like')
def update_likes():
  _id = int(flask.request.args.get('post_id'))
  #Do something to update the database
  return flask.jsonify({'success':'True'})
我建议返回一个
json
ified响应,这样您就可以处理可能发生的错误,例如用户喜欢两次帖子。如果您发现是这种情况,那么您可以返回
flask.jsonify({'success':'False')
,并在前端进行相应的处理

然后,在HTML中:

<html>
  <head>
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  </head>
  <div class='post_wrapper'>
    {%for p in posts%}
       <div id='post_{{post.id}}'>
         <p>{{p.author.username}} says:</p>
         <p>{{p.body}}</p>
         {%if p.upvotes%}
           <button class='upvote' id='upvote_{{p.id}}'>Like <span id='upvotes_{{p.id}}'>{{p.upvotes}}</span></p>
         {%else%}
            <button class='upvote' id='upvote_{{p.id}}'>Like <span id='upvotes_{{p.id}}'>0</span></p>
         {%endif%}  
       </div>
    {%endfor%}
  </div>
  <script>
    $(document).ready(function(){
      $('.post_wrapper').on('click', '.upvote', function(){
         var post_id = this.id.match('\\d+');
         $.ajax({
          url: "/update_like",
          type: "get",
          data: {post_id: post_id},
          success: function(response) {
            if (response.success === 'True'){
              var like_val = parseInt($('#upvotes_'+post_id).text()) + 1;
              $('#upvotes_'+post_id).text(like_val.toString());
            }
            else{
               alert('You already liked that post!');
            }
          }
         });
      });
    });
  </script>
</html>

{%p在posts%}
{{p.author.username}}说:

{{p.body}}

{%if p.upvows%} 像{p.upvoates}

{%else%} 像0

{%endif%} {%endfor%} $(文档).ready(函数(){ $('.post_wrapper')。on('单击','.upvote',函数(){ var post_id=this.id.match('\\d+'); $.ajax({ url:“/update\u like”, 键入:“获取”, 数据:{post_id:post_id}, 成功:功能(响应){ 如果(response.success=='True'){ var like_val=parseInt($('#upvows_u'+post_id).text())+1; $('#upvows'+post_id).text(如_val.toString()); } 否则{ 警惕(“你已经喜欢那篇文章了!”); } } }); }); });
好的,我已经成功了:

  • 这是我们的路线:

    @app.route(“/ulk”)
    def ulk():
    ppp=request.args.get('p',0,type=int)
    lpost=Post.query.filter_by(id=ppp.first())
    lpost.upvots+=1
    db.session.commit()
    返回jsonify(结果=ppp)

  • 下面是我们的HTML页面,其中包含一些jQuery:

    <html>
      <head>
         <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
      </head>
    
    
     <body>
     <script type=text/javascript>
      $(function() {
        $('a#like').bind('click', function() {
    
          $.getJSON('/ulk', {
            p: pid
          }, function(data) {
            $("#result2").text(data.result);
          });
          return false;
    
        });
      });
    </script>
    
     <br/><br/>
    {% for p in posts %}
    
     {% if p.upvotes %}
    {% set pupvotes = p.upvotes %}
    {% else %}
    {% set pupvotes = 0 %}
    {% endif %}
    
     <p>{{ p.author.username }} says: <b>{{ p.body }}</b>&nbsp;
             <a href="#" id=like>
                 <button id="{{ p.id }}" onclick="pid={{ p.id }};pvts = {{ pupvotes }} +1;myF1();">{{ pupvotes }} Likes</button>
             </a>
     </p>
    
     <script type=text/javascript>
     function myF1() {
        $( "#" + pid ).text(pvts + ' Likes');
    
        $('#' + pid).on('click', function() {
        $(this).prop('disabled', true);
    });
     }
    </script>
    
     {%endfor%}
    <br/>
     <span id=result2>...</span>
     </body>
    
    </html>
    
    
    $(函数(){
    $('a#like').bind('click',function(){
    $.getJSON(“/ulk”{
    p:pid
    },函数(数据){
    $(“#result2”).text(data.result);
    });
    返回false;
    });
    });
    

    {%p在posts%} {%if p.upvows%} {%set PupPolities=p.UPPOWETS%} {%else%} {%set=0%} {%endif%} {{p.author.username}说:{p.body}

    函数myF1(){ $(“#”+pid).text(pvts+'Likes'); $('#'+pid).on('click',function(){ $(this.prop('disabled',true); }); } {%endfor%}
    ...
    使用类而不是ID,并将该innerHTML应用于具有该类的所有元素您的JavaScript函数仍然不会将操作发送到Flask服务器。为此,您需要使用AJAX调用;将
    p.id
    值发送到AJAX端点,该端点随后更新数据库并返回新的likes计数,然后使用该计数更新
    innerHTML
    值。您将脚本标记放在哪里了?Solomon,我有函数myF1()。。。就在{%endfor%}之前-我应该把它去掉吗?如果我把它去掉,“p”变得没有定义。@andreykunikovs你能澄清一下它是怎么不起作用的吗?首先,你有一个拼写错误,
    {%forpost in posts%}
    ,在我们的例子中应该是
    {%forp in posts%}
    。同样
    其次,我怀疑Flask不支持您调用jQuery Ajax的方法。不过,我的工作方式是我自己的答案。
    <html>
      <head>
         <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
      </head>
      <div class='post_wrapper'>
        {%for p in posts%}
           <div id='post_{{post.id}}'>
             <p>{{p.author.username}} says:</p>
             <p>{{p.body}}</p>
             {%if p.upvotes%}
               <button class='upvote' id='upvote_{{p.id}}'>Like <span id='upvotes_{{p.id}}'>{{p.upvotes}}</span></p>
             {%else%}
                <button class='upvote' id='upvote_{{p.id}}'>Like <span id='upvotes_{{p.id}}'>0</span></p>
             {%endif%}  
           </div>
        {%endfor%}
      </div>
      <script>
        $(document).ready(function(){
          $('.post_wrapper').on('click', '.upvote', function(){
             var post_id = this.id.match('\\d+');
             $.ajax({
              url: "/update_like",
              type: "get",
              data: {post_id: post_id},
              success: function(response) {
                if (response.success === 'True'){
                  var like_val = parseInt($('#upvotes_'+post_id).text()) + 1;
                  $('#upvotes_'+post_id).text(like_val.toString());
                }
                else{
                   alert('You already liked that post!');
                }
              }
             });
          });
        });
      </script>
    </html>
    
    <html>
      <head>
         <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
      </head>
    
    
     <body>
     <script type=text/javascript>
      $(function() {
        $('a#like').bind('click', function() {
    
          $.getJSON('/ulk', {
            p: pid
          }, function(data) {
            $("#result2").text(data.result);
          });
          return false;
    
        });
      });
    </script>
    
     <br/><br/>
    {% for p in posts %}
    
     {% if p.upvotes %}
    {% set pupvotes = p.upvotes %}
    {% else %}
    {% set pupvotes = 0 %}
    {% endif %}
    
     <p>{{ p.author.username }} says: <b>{{ p.body }}</b>&nbsp;
             <a href="#" id=like>
                 <button id="{{ p.id }}" onclick="pid={{ p.id }};pvts = {{ pupvotes }} +1;myF1();">{{ pupvotes }} Likes</button>
             </a>
     </p>
    
     <script type=text/javascript>
     function myF1() {
        $( "#" + pid ).text(pvts + ' Likes');
    
        $('#' + pid).on('click', function() {
        $(this).prop('disabled', true);
    });
     }
    </script>
    
     {%endfor%}
    <br/>
     <span id=result2>...</span>
     </body>
    
    </html>