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

时间:2013-01-15 09:45:35

标签: 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(){ 
   $.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请求”消息。

thread中回答了类似的疑问。即使我使用那里提供的答案,代码也不起作用。

我猜测答案必须与“{{csrf_token}}”相关,但不确定如何......

任何类型的帮助都将受到赞赏。

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

如果这是因为csrf令牌(您可以使用firebug在浏览器中查看),请在views.py

中使用它
from django.views.decorators.csrf import csrf_exempt

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