Django:接受AJAX调用并呈现响应?

时间:2015-06-20 09:58:52

标签: jquery python ajax django call

这是我的javascript代码:

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');

    //Ajax call
    function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
        }
        $.ajaxSetup({
            crossDomain: false, // obviates need for sameOrigin test
            beforeSend: function(xhr, settings) {
                if (!csrfSafeMethod(settings.type)) {
                    xhr.setRequestHeader("X-CSRFToken", csrftoken);
                }
            }
    });

    $(".color_wheel").click(function() {
    $.ajax({
        url:'/',
        type: "POST",
        data: {num : level},
    });});

这是我的观点文件:

from django.shortcuts import render
from .models import Joke

# Create your views here.
def home_page(request):
    return render(request, 'home.html')

def joke_page(request):
    if request.POST:
        num = request.POST['num']     
        return render(request, 'joke.html', {'joke': Joke.find_joke(num)})

如您所见,我希望Django接受AJAX调用,获取给定的数字(num)并使用它来显示新页面。问题是,它不起作用......也许我做错了,也许整件事都错了......如果你知道如何,请帮助。谢谢!

编辑:

urls.py

from django.conf.urls import url

from jokes import views

urlpatterns = [
    url(r'^$', views.home_page, name='home_page'),
    url(r'^(?P<joke_id>[0-9]+)/$', views.joke_page, name='joke_page'),
]

1 个答案:

答案 0 :(得分:0)

我认为只需使用GET请求即可完成此操作

$(".color_wheel").click(function() {
    window.location.href = "/"+devel,
})

在视图中

def joke_page(request, joke_id):
    return render(request, 'joke.html', {'joke': Joke.find_joke(joke_id)})