我正在尝试让AJAX在Django(1.8)上运行。
我的问题来自$.ajax
方法,它没有将值发送到服务器。我必须将url
值的路由从更改为url: '/vote/'
,url: '/'
以便它可以工作(并且不返回404,但找不到),但是它不发送值(数据库未修改)。此外,在index.html
该<a href={% url 'views.vote' %}></a>
所以我使用返回一个错误<a href="/vote/"></a>
。
这是我所拥有的:
├── assets
│ ├── css
│ │ └── style.css
│ └── js
│ ├── app.js
│ └── jquery.js
├── db.sqlite3
├── manage.py
├── templates
│ └── index.html
├── values
│ ├── __init__.py
│ ├── admin.py
│ ├── migrations
│ │ ├── __init__.py
│ ├── models.py
│ ├── tests.py
│ ├── urls.py
│ └── views.py
└── votes
├── __init__.py
├── settings.py
├── urls.py
└── wsgi.py
values / models.py
from django.db import models
class Value(models.Model):
title = models.CharField(max_length=255)
points = models.IntegerField(default=1)
def __str__(self):
return self.title
投票/ urls.py
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$', include('values.urls')),
]
urlpatterns += staticfiles_urlpatterns()
值/网址
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', 'values.views.index'),
url(r'^vote/$', 'values.views.vote'),
]
值/ views.py
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from .models import Value
def index(request):
val = Value.objects.all()
return render(request, 'index.html', {'values': val})
def vote(request):
value = get_object_or_404(Value, pk=request.POST.get('value'))
value.points += 1
value.save()
return HttpResponse()
templates / index.html
{% load static from staticfiles %}
<html>
<head>
<title>My title</title>
<script src="{% static 'js/jquery.js' %}"></script>
<script src="{% static 'js/app.js' %}"></script>
<link rel="stylesheet" href="{% static 'css/style.css' %}">
</head>
<body>
<ul>
{% for foo in values %}
<li>
<p class="story-title">
{{ foo.title}}
</p>
<p class="points">
<a href="/vote/" class="vote" id="story-vote-{{ foo.id }}">{{ foo.points }} points </a>
</p>
</li>
{% endfor %}
</ul>
</body>
</html>
资产/js/app.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 (valueID) {
$.ajax({
type: 'POST',
url: '/',
data: { "value": valueID },
success: function () {
//$("#story-vote-" + valueID).hide();
$("#story-title-" + valueID).css({"margin-left": "15px"});
},
headers: {
'X-CSRFToken': csrftoken
}
});
return false;
}
$("a.vote").click(function () {
var valueID = parseInt(this.id.split("-")[2]);
return vote(valueID);
})
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
});
您的问题与您的Ajax无关。您的问题出在您的表决/urls.py中:您要包括其他以结尾为的模式的url $
,因此没有多余的匹配项。它应该是:
url(r'^', include('values.urls')),
(请注意1.9将明确警告此行为。)
现在,您可以将Ajax帖子的位置更改回正确的URL。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句