【问题标题】:jquery $.post, to django view method, request.method shows GET, and cannot retrieve parametersjquery $.post,到django查看方法,request.method显示GET,取不到参数
【发布时间】:2014-09-22 06:52:19
【问题描述】:

我试图弄清楚如何将一些数据发送到 django vis POST 中的视图,并根据请求中发送的数据,通过HttpResponse 从视图返回一些数据到客户端。

当客户端发送 POST 请求时,Web 控制台会打印,

POST http://<myurl>
GET  http://<myurl>/

返回的消息是“get”。在视图方法中,当我尝试通过response.GET.get("key")访问参数时,返回None

我一定是误会了什么,有人知道发生了什么吗?

views.py

    from django.http import HttpResponse

    def test(request):

        msg = ""

        if request.method == "POST":
            msg = "post"

        elif request.method == "GET":
            msg = "get"

        return HttpResponse(msg)

javascrip/jquery

  function _req(url, params, callback ) {

    function onResponse( data ) {
      console.log( data );    
      callback(data);
    };

    $.post(
      url,
      JSON.stringify(params),
      onResponse,
      "text");
   };

【问题讨论】:

  • 你没有显示方法是如何被调用的。
  • $.post 传递了对应于 urls.py 中定义的 test 的 url。

标签: django httprequest httpresponse


【解决方案1】:

打印的两个 URL 准确地显示了正在发生的事情。您发布到一个没有最后斜杠的 URL,但您有默认的 APPEND_SLASH 设置,因此 Django 重定向到附加了最后一个斜杠的 URL。重定向始终是 GET。

确保发布到带有斜杠的 URL。

【讨论】:

    猜你喜欢
    • 2012-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-27
    • 1970-01-01
    • 2013-03-03
    • 1970-01-01
    相关资源
    最近更新 更多