作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想实现投票功能。投票函数无法获取对象。 vote.js 应该没问题。任何想法?看来 POST 请求没有发送。谢谢。
这是错误:
Page not found (404)
Request Method: GET
Request URL: http://.../vote/
Raised by: book.views.vote
No Eintrag matches the given query.
result.html 中的片段:
<a href="/vote/" id="eintrag-vote-{{ eintrag.id }}" class="vote">▲</a>
<p id="eintrag-title-{{ eintrag.id }}">{{ eintrag.title }}</p>
模型.py:
class Eintrag(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
title = models.CharField(max_length=200)
points = models.IntegerField(default=1)
text = models.TextField()
views.py:
@login_required
def vote(request):
eintrag = get_object_or_404(Eintrag, id=request.POST.get('eintrag'))
eintrag.points += 1
eintrag.save()
return HttpResponse()
url.py:
url(r'^vote/$', views.vote, name='vote'),
和 vote.js:
$(document).ready(function() {
// using jQuery
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
function.vote(eintragID) {
$.ajax({
type: "POST",
url: "/vote/",
data: {
"eintrag": eintragID
},
success: function() {
$("#eintrag-vote-" + eintragID).hide();
$("#eintrag-title-" + eintragID).css({
"margin-left": "15px"
});
},
headers: {
'X-CSRFToken': csrftoken
}
});
return false;
}
$("a.vote").click(function() {
var eintragID = parseInt(this.id.split("-")[2]);
return vote(eintragID);
})
});
最佳答案
您的请求方法似乎不匹配。当您应该执行 POST 时,您却执行了 GET。
此行引发 404,因为没有 request.POST
:
eintrag = get_object_or_404(Eintrag, id=request.POST.get('eintrag'))
我邀请您使用 django.views.decorators.http.require_POST
装饰此 View ,以便您收到更好地反射(reflect)方法问题的 HTTP 405 Method not allowed 错误
比 404
我认为它来自于你的 Ajax 请求在 JS 中的完成方式(参见 http://api.jquery.com/jquery.ajax/ )
您可以尝试更改以下内容吗?
function vote(eintragID) {
$.ajax({
...
关于javascript - 投票功能 "No Eintrag matches the given query",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37776307/
我是一名优秀的程序员,十分优秀!