完成ajax模拟登录的联系

master
RogerWork 1 year ago
parent 907bdfed12
commit d9f1e705ac
  1. 2
      form_demo/urls.py
  2. 14
      form_demo/views.py
  3. 35
      templates/form_demo/ajax_login.html

@ -10,4 +10,6 @@ urlpatterns = [
path('userinfomodel/', views.userinfo_model_form),
path('userinfomodelsave/', views.userinfo_model_from_save),
re_path(r'media/(?P<path>.*)', serve, {'document_root': settings.MEDIA_ROOT}),
path('login/', views.ajax_login),
path('logindata/', views.ajax_login_data)
]

@ -1,4 +1,5 @@
from django.shortcuts import render
from django.http import JsonResponse
from .forms import *
@ -77,3 +78,16 @@ def userinfo_model_from_save(request):
print(errors)
return render(request, 'form_demo/userinfomodels.html', {'form_obj': f, 'errors': errors})
return render(request, 'form_demo/userinfomodels.html', {'form_obj': f})
def ajax_login(request):
return render(request, 'form_demo/ajax_login.html')
def ajax_login_data(request):
username = request.POST.get('username')
password = request.POST.get('password')
if username == 'admin' and password == 'admin123':
return JsonResponse({'code': 1, 'msg': '登录成功'})
else:
return JsonResponse({'code': 0, 'msg': '登录失败'})

@ -0,0 +1,35 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
{% csrf_token %}
{% load static%}
<script src={% static '/plugins/jquery-3.7.0.js' %}></script>
<body>
用户名:<input type="text" id="username">
密码: <input type="password" id="password">
<button type="submit" id="submit">提交</button>
</body>
<script>
$("#submit").click(function() {
$.ajax({
url: "/logindata/",
type: "POST",
data: {
username: $("#username").val(),
password: $("#password").val(),
"csrfmiddlewaretoken": $("[name='csrfmiddlewaretoken']").val()
},
success: function (data) {
console.log(data);
alert(data.msg);
},
error: function (jqXHR, textStatus, err) {
console.log(arguments)
},
})
})
</script>
</html>
Loading…
Cancel
Save