Jquery$post请求在Django中不起作用

Jquery$post请求在Django中不起作用,jquery,django,post,get,Jquery,Django,Post,Get,我试图将来自javascript的$post请求用于我的django模板,但我缺少了一些东西,因为它不起作用 我将向您展示我的代码: 这是模板: //TEMPLATE //This code will send a string to django "views.py" file, //then it will show a pop up message from the data retreived from "views.py" function test_post(){ $.po

我试图将来自javascript的$post请求用于我的django模板,但我缺少了一些东西,因为它不起作用

我将向您展示我的代码:

这是模板:

//TEMPLATE
//This code will send a string to django "views.py" file,
//then it will show a pop up message from the data retreived from "views.py"

function test_post(){ 
   $.post("/xhr_test", 
      {name: "Monty", food: "Spam", csrftoken : "{{ csrf_token }}" },

      function(data) {
          alert(data)
      ;}); 
};
这是views.py:

// VIEWS.PY
//Depending on the type of request it will send a message or another.


def xhr_test(request):
    if request.is_ajax():
        if request.method == 'GET':
            message = "This is an XHR GET request"
        elif request.method == 'POST':
            message = "This is an XHR POST request"
            # Here we can access the POST data
            print request.POST
    else:
        message = "No XHR"
    return HttpResponse(message)
这段代码没有显示“这是一个XHR POST请求”消息。但是,在使用$GET请求时,它确实会显示“这是一个XHR GET请求”消息

类似的疑问也在这方面得到了回答。即使我使用的是那里提供的答案,代码也不起作用

我猜答案一定与“{{csrf_token}}”有关,但不确定如何


任何类型的帮助都将不胜感激。

如果您遵循默认方式使用
django.middleware.csrf.CsrfViewMiddleware
,则csrf令牌的正确post键为
csrfmiddlewaretoken


但是,您应该查看CSRF中的AJAX部分。

如果这是由于CSRF令牌造成的(您可以使用firebug在浏览器中检查它),那么在您的views.py中使用它

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def xhr_test(request):
   ...........

您如何填充csrf_令牌?为什么要禁用csrf保护?每当我们在模板中使用ajax或jquery时,我们通常会得到csrf令牌的错误,即使我们使用的是中间件,所以这是检查是否存在另一个错误或只是csrf缺失错误的一种方法。我不是强迫任何人使用它,而是只是为了测试目的。显然Inforian告诉我使用“csrf_豁免”进行调试。我从来没有听说过firedebug,它真的很有帮助。它与@csrf_豁免一起工作。然而,并非没有它。我会仔细阅读firedbug告诉我的建议,我会让你知道的。