【问题标题】:QueryDict always empty from AJAX POSTAJAX POST 中的 QueryDict 始终为空
【发布时间】:2014-11-05 15:59:24
【问题描述】:

我看到有人问过其中一些问题,但我尝试实施他们的解决方案,但对我没有用。

我正在尝试使用 POST 向 django 视图发送一个基本的 AJAX 请求。这是我的 JQuery:

$('#save-button').click(function() {
    var names = ['BLOGGS Joe', 'SMITH John'];
    data = JSON.stringify(names);
    $.ajax({
        "contentType": "application/json; charset=utf-8",
        "data": data,
        "url" : "/ajax/myteam/save/",
        "type": "POST",
        "success": function(response) {

        }
    });
});

这是我的 Django 视图:

def myteam_save(request):
   if request.method == 'POST':
       if request.POST:
           print 'Hurray'
       else:
           print 'Boo'
       response = HttpResponse(json.dumps({'code':'ok'}), content_type='application/json')
       return response

当我检查 Firebug 中发生的事情时,我发现帖子正在按我的意图进行,但 request.POST 中的 QueryDict 对象始终为空。

我一直很小心我认为的 csrf 令牌,甚至尝试在我的设置中关闭“django.middleware.csrf.CsrfViewMiddleware”,但这似乎没有效果。

我做错了什么?

感谢您的帮助!

【问题讨论】:

  • "contentType": "application/json; charset=utf-8" 您没有将 JSON 发送到服务器。此外,应该是 dataType:'json' 告诉 success functionresponse 视为可解析的 JSON 对象。就django响应而言...直接访问页面,调试直到得到输出,验证输出确实是json。
  • @Ohgodwhy 感谢您的回复。内容类型只是我试图匹配其他人的代码来解决问题而忘记改回来。直接访问页面是什么意思(对不起,如果是愚蠢的问题)?

标签: jquery ajax django


【解决方案1】:

Django 并没有真正为您反序列化 JSON 有效负载。 request.POST 用于 HTML 发布的表单等。

对于JSON有效载荷,您应该自己反序列化请求正文,例如:json.loads(request.body)

request.body 是您访问原始负载的方式)。

【讨论】:

    【解决方案2】:

    正如@Sergio 所说,您需要在views.py 中解码request.body。这是使用Django 3.1Fetch 的解决方案。

    def myteam_save(request):
        if request.method == 'POST' and request.headers.get("contentType": "application/json"):
            body_unicode = request.body.decode('utf-8')
            received_json = json.loads(body_unicode)
    
        return JsonResponse(received_json, safe=False)
    

    我不熟悉AJAX。所以我发布了典型的POSTXHR 应该如何使用Fetch。假设varKeyvarValue 是预定义变量,其值作为json 发送:

    根据official documentation,出于安全原因,您必须通过它。

    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                // 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;
    }
    const csrftoken = getCookie('csrftoken');
    

    下面是使用Fetch完成的实际XHR

    dict = { [varKey]: varValue }
    
    fetch("http://127.0.0.1:8000/bot/api/post/45/", {
        headers: {
            'X-CSRFToken': csrftoken,
            "x-Requested-With": "XMLHttpRequest",
            "Content-Type": "application/json"
        },
        method: 'POST',
        body: JSON.stringify(dict),
        mode: 'same-origin',
    })
    

    【讨论】:

      猜你喜欢
      • 2016-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-01
      • 2020-05-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多