我想讓AJAX在Django(1.8)上工作。通過AJAX修改數據庫值
我的問題來自$.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
值/ 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()
模板/ 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);
}
}
});
});
我不明白你爲什麼改變了URL。 '/'進入投票指數,而不是投票視圖。 –
我剛剛做到了,因爲這是連接到服務器而不會出錯的唯一方法。如果我使用'url:/ vote /',則會拋出'404 not found'。 – Rod