我试图让AJAX在Django(1.8)上工作。
我的问题来自meteor add wolves:bourbon@3.1.0
meteor add wolves:neat@3.1.0
方法,它没有将值发送到服务器。我必须将$.ajax
值的路由从url
更改为url: '/vote/'
,以便它可以正常工作(并且不会返回404找不到),但它不会发送值(数据库)没有修改)。同样在url: '/'
中,index.html
会返回错误,因此我使用<a href={% url 'views.vote' %}></a>
。
这就是我所拥有的:
<a href="/vote/"></a>
值/ models.py
├── 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
票/ urls.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
值/网址
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()
值/ views.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', 'values.views.index'),
url(r'^vote/$', 'values.views.vote'),
]
模板/ index.html中
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()
资产/ JS / app.js
{% 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>
答案 0 :(得分:0)
您的问题与您的Ajax无关。您的问题出在您的投票/ urls.py中:您包含的其他网址的格式以$
结尾,因此不会有任何额外匹配。它应该是:
url(r'^', include('values.urls')),
(请注意,1.9会明确警告此行为。)
现在,您可以将Ajax帖子的位置更改回正确的URL。