2015-10-14 63 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