【问题标题】:Ajax post request return empty querydictAjax 发布请求返回空查询字典
【发布时间】:2017-11-19 00:33:45
【问题描述】:

我正在尝试发送发布请求并根据该信息对用户进行身份验证。然而,即使我检查了来自$('#sign_in').serialize() 的结果并且它返回类似username=test&password=test 的内容,当我在views.py 中运行print(request.POST) 时它仍然返回<QueryDict: {}>。我做错了什么,为什么不传递参数?

ajax 函数

function logIn() {
    var username = $('#id_username').val();
    var password = $('#id_password').val();
    console.log($('#sign_in').serialize())
    $('#sign_in_btn').text('Logger ind...');
    $.ajax({
        url: "/account/login/",
        type: "POST",
        dataType: 'json',
        contentType: 'application/json',
        data: $('#sign_in').serialize(),
        success: function (data) {
            console.log(data)

        }, error: function (error) {

        }
    });
}

views.py

def login(request):
    print(request.POST)
    if request.method == "POST":
        form = SignInForm(data=request.POST)
        response_data = {}
        if form.is_valid():
            username = request.POST.get("username", False)
            password = request.POST.get("password", False)
            user = authenticate(username=username, password=password)
            auth_login(request, user)
            if user:
                response_data['success'] = True
                response_data['message'] = 'Brugeren er blevet oprettet!'
        else: #invalid case
            response_data['success'] = False
            response_data['message'] = 'Forkert brugernavn/kodeord. Prøv venligst en anden kombination eller tryk på glemt kodeord!'
            print(form.errors)
        return HttpResponse(json.dumps(response_data), content_type='application/json')
    else:
        form = SignInForm()
    return render(request, 'login.html', {'form': form})

【问题讨论】:

    标签: python ajax django


    【解决方案1】:

    您需要将 contentType 改为 application/x-www-form-urlencoded 或将其留空,因为其默认值为 application/x-www-form-urlencoded;charset=UTF-8

    事情是.serialize()返回表单的内容 URL 编码不是 JSON。

    【讨论】:

      【解决方案2】:

      lcastillov 已经回答了你的问题,但是如果你想将 json 数据发送到服务器,这里有几件事你应该注意。

      您将在 request.data 中获取数据,因为您已将 contentType 设置为 application/json

      $.ajax() 函数的 data 属性也应该是 json 格式

      data: {
         "username": "test",
         "password": "test"
      } 
      

      现在您可以轻松地在视图中获取数据

      request.data["username"]
      request.data["password"]
      

      request.POST 用于具有 contentType 的表单编码数据 application/x-www-form-urlencoded

      【讨论】:

        猜你喜欢
        • 2022-07-05
        • 2017-07-23
        • 2021-07-15
        • 2012-11-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-23
        • 2018-12-05
        相关资源
        最近更新 更多