如何在jQueryAjax响应中获取Id值?
在Django应用程序中,我希望在ajax响应中获得ID值: 视图.py如何在jQueryAjax响应中获取Id值?,jquery,django,Jquery,Django,在Django应用程序中,我希望在ajax响应中获得ID值: 视图.py def like_piccomment(request, cid): if request.method == 'POST': the_comment = PicComment.objects.get(id= cid) the_photo = the_comment.pic who_liked = request.user.id if PicCom
def like_piccomment(request, cid):
if request.method == 'POST':
the_comment = PicComment.objects.get(id= cid)
the_photo = the_comment.pic
who_liked = request.user.id
if PicCommentLike.objects.filter(liker=who_liked, liked=cid):
the_comment.likes -=1
the_comment.save()
PicCommentLike.objects.filter(liker=who_liked, liked=cid).delete()
else:
the_comment.likes +=1
the_comment.save()
newliker = PicCommentLike(liker=who_liked, liked=cid)
newliker.save()
args = {}
args.update(csrf(request))
args['likes'] = the_comment.likes
args['cid'] = cid
return render_to_response('userpics/likes.html', args)
likes.html
{% if likes > 0 %}
{{likes}}
<i id="{{cid}}">liked</i>
{% else %}
<i id="{{cid}}">No one liked yet</i>
{% endif %}
{%if likes>0%}
{{likes}
喜欢
{%else%}
还没有人喜欢
{%endif%}
并将ajax响应传递给这个jquery likeSuccess函数:
<script>
//ajax send function which works fine
//deal with ajax response
function likeSuccess(data, textStatus, jqXHR) {
//these lines don't work
var cid = $(data).find("#id").text();
$('#'+ cid).html(data);
alert("dom id:" + cid); //just to check }
</script>
function likeSuccess(data, textStatus, jqXHR)
{
var cid = $(data).attr('title')
$('#'+ cid).html(data);
}
//ajax发送函数,运行良好
//处理ajax响应
类似success的函数(数据、textStatus、jqXHR){
//这些线不行
var cid=$(数据).find(#id”).text();
$('#'+cid).html(数据);
警报(“dom id:+cid);//仅用于检查}
困难在于从模板中获取ID值,以便ajax响应只出现在相关ID上
我是jquery的noob,尝试了许多不同的解决方案,但都没有成功。谢谢你的提示 请检查以下内容以供参考 我最近遇到了这样的问题。。。但我使用了jquery的post方法 从视图中,您可以创建响应并发送,如下所示
return HttpResponse(json.dumps({'message': 'success','something':'message'}))
jquery将像这样运行
$(".likecomment").click(function() {
var $this = $(this);
var cid = $this.attr('id');
$.post('/pic/like_comment'+cid, $(this).serialize(), function(data){
result = JSON.parse(data);
if(result.message == 'success')
{
yourfunction();
}
});
});
多亏了哈迪斯提出的观点,我设法以最小的麻烦解决了这个问题,如下所示: likes.html
<i title="{{cid}}">
{% if likes > 0 %}
{{likes}} Liked
</i>
{% else %}
No one liked yet
</i>
您需要显示处理ajax帖子的Django视图代码。@Brandon我添加了视图,虽然不需要,因为“cid”可以很好地传递给模板。那么您想问什么?你说cid没有传递给模板,现在你说是的。@DanielRoseman对不起,希望我消除了我解释的歧义。问题在于解析ajax响应。django部分很好。这很有趣,但由于我的观点是基于post的,我不确定如何处理序列化csrf等,我宁愿坚持我自己的笨拙方式,只解决jquery解析问题。@HadeS你是对的。OP需要查找
{{cid}
,因为该值将被分配给
标记的id
属性。