GET请求
Jquery代码(调用视图发送邮箱验证码)
$(document).ready(function() { // 获取发送验证码的按钮 var btn = $('#send_code'); // 设置按钮为禁用状态 btn.prop('disabled', true); // 监听邮箱输入框的变化 $('#email').on('input', function() { // 启用按钮 btn.prop('disabled', false); }); // 点击发送验证码的按钮 btn.click(function() { // 获取用户输入的邮箱 var email = $('#email').val(); // 发送ajax请求,向邮箱发送验证码 $.ajax({ url: "/user/send_code/", // 根据您的实际情况修改为后端接口地址 data: {'email': email}, type: 'GET', dataType: 'json', success: function(data) { if (data.status === 'success') { // 发送成功,显示提示信息,禁用按钮,倒计时 btn.text('发送成功'); btn.prop('disabled', true); var seconds = 60; var timer = setInterval(function() { seconds -= 1; btn.text(seconds + '秒后可重新发送'); if (seconds === 0) { // 倒计时结束,启用按钮,重置文本 btn.prop('disabled', false); btn.text('发送验证码'); clearInterval(timer); } }, 1000); } else { // 发送失败,显示提示信息 btn.text('发送失败,请重试'); } } }); // 阻止按钮的默认行为 return false; }); });
python代码(视图函数,用于产生随机验证码)
def send_code(request): # 用于创建验证码对象 res = {'status': 'success', 'info': 'ok'} email = request.GET['email'] code = '' for i in range(6): n = random.randint(0, 9) b = chr(random.randint(65, 90)) s = chr(random.randint(97, 122)) code += str(random.choice([n, b, s])) mail.send_mail("验证码", code, sender, recipient_list=[email]) checkcode.objects.create(email=email, code=code, create_time=time.time()) return JosnResponse(res)
POST请求
Jquery代码(发送数据验证请求并跳转)
$('#submit').on('click', function() { const username = $('#username').val(); const password = $('#password').val(); const code = $('#code').val(); const career = $('#careers').val(); const email = $('#email').val(); $.ajax({ url: '/user/register/', // 根据您的实际情况修改为后端接口地址 type: 'POST', data: JSON.stringify({ username, password, email, career, code }), contentType: 'application/json', success: function(data) { console.log(data); // 在控制台打印出data的内容 if (data.status == 'error') { alert(data.message); // Display error message } else { alert('User registered successfully'); // Show success message window.location.href = '/index'; // Redirect to another page } }, error: function(xhr, status, error) { console.error('Error during registration:', error); } }); return false; });
python代码(数据校验,数据库存储)
def register(request): if request.method == 'GET': return render(request, 'login/register.html') elif request.method == 'POST': data = json.loads(request.body) email = data.get('email') username = data.get('username') code = data.get('code') password = data.get('password') career = data.get('career') res = {'status': 'error', 'message': ''} # 校验用户是否存在 try: # 排除并发写入时引发的索引重复,相同的uesrname插入 old_users = User.objects.filter(email=email) except Exception as e: res['message'] = '用户已存在' return JsonResponse(res) if old_users: res['message'] = '用户已存在' return JsonResponse(res) # 校验验证码是否过期 codes = checkcode.objects.filter(email=email, is_active=True) if not codes: res['message'] = '验证码未发送或失效' return JsonResponse(res) sign = False for real in codes: real.is_active = False real.save() oldtime = float(real.create_time) if (time.time() - oldtime) 10: res['message'] = '用户名长度不合法' return JsonResponse(res) # 对密码进行哈希存储 pwd = hashlib.md5() pwd.update(password.encode()) pwd_new = pwd.hexdigest() User.objects.create(username=username, email=email, password=pwd_new, career=career) request.session['username'] = username request.session['email'] = email res['status'] = 'success' res['message'] = '注册成功' return JsonResponse(res)
小结
对于这种有可能需要停留在原页面,保持原有状态的,前端一律采用Jquery能省很多事

(图片来源网络,侵删)
因为常规的视图函数返回结果是HttpResponse或者HttpRedirectResponse
这种响应结果会直接渲染在html页面上,不符合我们的业务逻辑

(图片来源网络,侵删)
视图函数中定义字典,字典类型可以在不报错的情况下转为JsonResponse
而在前端中拿到的响应结果必须是json数据(否则无法进行对data属性的调用),
换言之后端返回的响应体必须是JsonResponse,仅仅用json.dumps(res)还是不够,前端仍然无法调到正确响应结果
对于django中的路由
个人觉得,只要不影响的情况下,想省事一点,对于有访问不到的路由(末尾有无斜杠会导致各种错误的),可以把有斜杠和没有斜杠都写着,那样是最保险的写法,因为完全不需要django帮我们补全末尾斜杠(如果是django帮我们补全的话,访问的时候相当于重定向,如果此时还是post请求,那么会造成数据的丢失)所以在路由这块最好把两种形式都写上