我正在尝试发送一个名为' petadid'的整数。从这个js到django视图叫做petadlikeview'。但看起来数据并没有在视图中出现。如果我打印出了“petadid'在视图中,它显示“无”。谁能告诉我有什么问题?我是ajax和django的新手。
这是我的js:
<script>
$(document).ready(function(argument) {
$.ajaxSetup({cache:false});
var element = document.getElementById("likes");
var petadid = $(this).attr("data-petadid");
element.addEventListener("click",function(){
var req = new XMLHttpRequest();
req.open("POST",'/petadlike/')
req.onload = function(){
console.log(req.responseText);
console.log(petadid);
var data = JSON.parse(req.responseText);
}
req.setRequestHeader("X-CSRFToken", '{{ csrf_token }}');
var data = {
'petadid':petadid,
}
req.send(data);
});
});
</script>
这是我的django-view:
def petadlikeview(request):
print("vau")
if request.method=="POST":
print("vai")
petadid = request.POST.get('petadid')
print(petadid)
petad = PetAd.objects.get(pk=petadid)
like_count = petad.petadlikes_set.all().count()
like, created = petadlikes.objects.get_or_create(user=request.user,petad=petad)
print(created)
if created is False:
petadlikes.objects.get(user=request.user,petad=petad).delete()
like_count -= 1
liked = False
else:
like.save()
like_count += 1
liked = True
dict = {'like_count':like_count}
return JsonResponse(dict)
return HttpResponse(str(like_count)+' people have liked this')
else:
return HttpResponse('Bad Request')
答案 0 :(得分:1)
XMLHttpRequest不会像jQuery那样自动将对象转换为POST数据,您需要自己创建URL编码的字符串。
var data = "petadid=" + encodeURIComponent(petadid);
另外
var petadid = $(this).attr("data-petadid");
应该是
var petadid = $(element).attr("data-petadid");