1.需求:实现点赞点灭,同一用户对一篇文章不可重复点赞和点灭,要求把数量显示出来
2.方法:建两张表(一张也可以),分别保存点赞的文章id+用户,点灭的文章id+用户名
3.使用异步的方法减少服务器负载
4.见代码
5.jquery平时不怎么用,用起来确实方便
6.需要学习:mysql db.session.add等操作 ajax的使用方法,jquery元素选择器,变量的选择(长见识) python部分对传进来的数据进行处理
js部分(post方法)
/**
* Created by Mr.Bean on 2018/2/21.
*/
var data = {
"flag": "False",
"mz":"zan",
"num": 0,
};
$(document).ready(function(){
$("#submit").addClass("btn btn-info");
$("span").unbind('click').bind('click',function () {
var article_id =$(this).attr("id");
var another = $(this).attr("value");
if(typeof(another)==="undefined"){
data.flag="True";
data.num = article_id;
data.mz="zan";
$.ajax({
type: "POST",
url: "/comment?t="+Math.random() ,
cache: false,
data: JSON.stringify(data),
contentType:'application/json;charset=UTF-8',
dataType:'json',
async: true,
success:function(data){
if(data.alert=="success"){
$("[id="+article_id+"]").html("赞"+ data.result);
}
else if(data.alert=="failed") alert("你已经点过赞了");
},
error:function (xhr,type) {
}
});
}
else{
data.flag="True";
data.num = another;
data.mz="mie";
$.ajax({
type: "POST",
url: "/comment?t="+Math.random() ,
data: JSON.stringify(data),
contentType:'application/json;charset=UTF-8',
dataType:'json',
success:function(data){
if(data.alert=="success"){
$("[value="+another+"]").html("灭-"+ data.result);
}
else if(data.alert=="failed") alert("你已经点灭过了");
},
error:function (xhr,type) {
}
})
}
});
});
html部分
{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}
{% block page_content %}
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script src="{{url_for('static', filename = 'ajax.js')}}"></script>
<style>
i {
font-style: normal;
font-size: 12px;
}
.ys {
color: #3a6fb9;
}
</style>
<div>
{{wtf.quick_form(form)}}
</div>
<div style="margin-top: 10px">
<span class="glyphicon glyphicon-heart-empty" style="font-weight: bold"> 评论区</span>
</div>
<ul class="posts">
{% for post in posts %}
<li class="post">
<div class="post-body">
<span class="glyphicon glyphicon-hand-right" aria-hidden="true">
{{post.article}}
</span>
</div>
<div>
<span style="float:left">
<i class="ys">{{ post.name}}</i>
<i style="color: #A8A7BE">{{ post.timestamp}}</i>
</span>
<span style="background-color: #434F77;float: right" class="badge badge-info" value="{{post.id}}"> 灭-{{post.mie}} </span>
<span style="background-color: #0079D7;float: right" class="badge badge-info" id="{{post.id}}"> 赞{{post.zan}} </span>
</div>
<hr>
</li>
{% endfor %}
</ul>
{% endblock %}
views.py
@main.route('/comment', methods=['GET', 'POST'])
@login_required
def comment():
form = PostForm()
data = request.get_json()
if data is not None:
emm = data.get('mz')
a = data.get('num')
if a is not None:
num = int(a)
if emm == "zan":
flag = data.get('flag')
number = Zan.query.filter_by(article_id=num).count()
if flag == 'True':
name = Zan.query.filter_by(article_id=num, name=session.get('name')).first()
if name is None:
new = Zan(article_id=num, name=session.get('name'))
db.session.add(new)
number += 1
user = Post.query.filter_by(id=num).first()
user.zan = number
db.session.add(user)
db.session.commit()
return jsonify({'result': number, 'alert': 'success'})
else:
return jsonify({'result': number, 'alert': 'failed'})
elif emm == "mie":
flag = data.get('flag')
number = Mie.query.filter_by(article_id=num).count()
if flag == 'True':
name = Mie.query.filter_by(article_id=num, name=session.get('name')).first()
if name is None:
new = Mie(article_id=num, name=session.get('name'))
db.session.add(new)
number += 1
user = Post.query.filter_by(id=num).first()
user.mie = number
db.session.add(user)
db.session.commit()
return jsonify({'result': number, 'alert': 'success'})
else:
return jsonify({'result': number, 'alert': 'failed'})
elif form.validate_on_submit():
post = Post(title=form.title.data, name=form.name.data, article=form.text.data, timestamp=datetime.utcnow(),
zan=0)
post.zan = 0
db.session.add(post)
db.session.commit()
return redirect(url_for('main.comment'))
posts = Post.query.order_by(Post.timestamp.desc()).all()
return render_template('main/comment.html', form=form, posts=posts)
效果图:
有些代码是可以精简的,我这里嫌麻烦懒得删了,可以对照着自己的需求改!