gpt4 book ai didi

python - Ajax post请求返回空querydict

转载 作者:太空宇宙 更新时间:2023-11-03 14:29:54 27 4
gpt4 key购买 nike

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

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})

最佳答案

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

The thing is .serialize() returns the content of the form URL-encoded not as JSON.

关于python - Ajax post请求返回空querydict,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47372572/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com