Flask接收Ajax的post数据实现局部刷新

Zss 发表于:

在前端页面显示一个点赞的按钮,每次点赞后数字加1,将数值返回到后端,后端再存储起来

当新的页面打开后,后端返回最新的点赞数到前端

jquery-1.8.3.min

    <script>
   $(function(){
      $("#praise").click(function(){
         var praise_img = $("#praise-img");
         var text_box = $("#add-num");
         var praise_txt = $("#praise-txt");
         var num=parseInt(praise_txt.text());
         var count = num +=1;

         $.ajax({
               url:"/",    //请求的url地址
               dataType:"json",   //返回格式为json
               data:{"like":count},    //参数值,键值对
               type:"POST",   //请求方式
               success:function(req){

               }
            });

         if(praise_img.attr("src") == ("../static/img/zan.png")){
            $(this).html("<img src='../static/img/yizan.png' id='praise-img' class='animation' />");
            praise_txt.addClass("hover");
            text_box.show().html("<em class='add-animation'>+1</em>");
            $(".add-animation").removeClass("hover");
            praise_txt.text(num)
         }
      });
   })
</script>
def like():
    with open('like.txt') as f:
        return int(f.read())

@app.route('/',methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        with open('like.txt','w') as f:
            f.write(request.form.get('like'))
        return render_template('index.html',like=like(),imagename=random.randint(1,5))
    else :
        return render_template('index.html',like=like(),imagename=random.randint(1,5))