2015-10-14 62 views
-1

我想让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); 
     } 
    } 
}); 


}); 
+0

我不明白你为什么改变了URL。 '/'进入投票指数,而不是投票视图。 –

+0

我刚刚做到了,因为这是连接到服务器而不会出错的唯一方法。如果我使用'url:/ vote /',则会抛出'404 not found'。 – Rod

回答

0

您的问题无关,与你的阿贾克斯。您的问题出现在您的投票/ urls.py中:您正在使用以$结尾的模式包含其他网址,因此没有任何额外内容可以匹配。它应该是:现在

url(r'^', include('values.urls')), 

(需要注意的是1.9会警告有关此问题的明确)

,你可以改变你的Ajax的帖子做回正确的URL的地方。

+0

现在'xhr'被加载,但是我在'http:// localhost/vote'上得到了'500错误'。这是为什么发生? '/ vote'已经在我的视图中定义过了。 – Rod

+0

不知道。你必须看看错误;你应该能够通过浏览器的开发工具看到它。 –

+0

我明白了。感谢您的帖子的解决方案。 – Rod