当前位置:   article > 正文

关于Django使用Jquery异步刷新

关于Django使用Jquery异步刷新

GET请求

Jquery代码(调用视图发送邮箱验证码)

  1. $(document).ready(function() {
  2. // 获取发送验证码的按钮
  3. var btn = $('#send_code');
  4. // 设置按钮为禁用状态
  5. btn.prop('disabled', true);
  6. // 监听邮箱输入框的变化
  7. $('#email').on('input', function() {
  8. // 启用按钮
  9. btn.prop('disabled', false);
  10. });
  11. // 点击发送验证码的按钮
  12. btn.click(function() {
  13. // 获取用户输入的邮箱
  14. var email = $('#email').val();
  15. // 发送ajax请求,向邮箱发送验证码
  16. $.ajax({
  17. url: "/user/send_code/", // 根据您的实际情况修改为后端接口地址
  18. data: {'email': email},
  19. type: 'GET',
  20. dataType: 'json',
  21. success: function(data) {
  22. if (data.status === 'success') {
  23. // 发送成功,显示提示信息,禁用按钮,倒计时
  24. btn.text('发送成功');
  25. btn.prop('disabled', true);
  26. var seconds = 60;
  27. var timer = setInterval(function() {
  28. seconds -= 1;
  29. btn.text(seconds + '秒后可重新发送');
  30. if (seconds === 0) {
  31. // 倒计时结束,启用按钮,重置文本
  32. btn.prop('disabled', false);
  33. btn.text('发送验证码');
  34. clearInterval(timer);
  35. }
  36. }, 1000);
  37. } else {
  38. // 发送失败,显示提示信息
  39. btn.text('发送失败,请重试');
  40. }
  41. }
  42. });
  43. // 阻止按钮的默认行为
  44. return false;
  45. });
  46. });

python代码(视图函数,用于产生随机验证码)

  1. def send_code(request):
  2. # 用于创建验证码对象
  3. res = {'status': 'success', 'info': 'ok'}
  4. email = request.GET['email']
  5. code = ''
  6. for i in range(6):
  7. n = random.randint(0, 9)
  8. b = chr(random.randint(65, 90))
  9. s = chr(random.randint(97, 122))
  10. code += str(random.choice([n, b, s]))
  11. mail.send_mail("验证码", code, sender, recipient_list=[email])
  12. checkcode.objects.create(email=email, code=code, create_time=time.time())
  13. return JosnResponse(res)

POST请求

Jquery代码(发送数据验证请求并跳转)

  1. $('#submit').on('click', function() {
  2. const username = $('#username').val();
  3. const password = $('#password').val();
  4. const code = $('#code').val();
  5. const career = $('#careers').val();
  6. const email = $('#email').val();
  7. $.ajax({
  8. url: '/user/register/', // 根据您的实际情况修改为后端接口地址
  9. type: 'POST',
  10. data: JSON.stringify({ username, password, email, career, code }),
  11. contentType: 'application/json',
  12. success: function(data) {
  13. console.log(data); // 在控制台打印出data的内容
  14. if (data.status == 'error') {
  15. alert(data.message); // Display error message
  16. } else {
  17. alert('User registered successfully'); // Show success message
  18. window.location.href = '/index'; // Redirect to another page
  19. }
  20. },
  21. error: function(xhr, status, error) {
  22. console.error('Error during registration:', error);
  23. }
  24. });
  25. return false;
  26. });

python代码(数据校验,数据库存储)

  1. def register(request):
  2. if request.method == 'GET':
  3. return render(request, 'login/register.html')
  4. elif request.method == 'POST':
  5. data = json.loads(request.body)
  6. email = data.get('email')
  7. username = data.get('username')
  8. code = data.get('code')
  9. password = data.get('password')
  10. career = data.get('career')
  11. res = {'status': 'error', 'message': ''}
  12. # 校验用户是否存在
  13. try: # 排除并发写入时引发的索引重复,相同的uesrname插入
  14. old_users = User.objects.filter(email=email)
  15. except Exception as e:
  16. res['message'] = '用户已存在'
  17. return JsonResponse(res)
  18. if old_users:
  19. res['message'] = '用户已存在'
  20. return JsonResponse(res)
  21. # 校验验证码是否过期
  22. codes = checkcode.objects.filter(email=email, is_active=True)
  23. if not codes:
  24. res['message'] = '验证码未发送或失效'
  25. return JsonResponse(res)
  26. sign = False
  27. for real in codes:
  28. real.is_active = False
  29. real.save()
  30. oldtime = float(real.create_time)
  31. if (time.time() - oldtime) <= 300 and code == real.code:
  32. sign = True
  33. if not sign:
  34. res['message'] = '未获取到有效验证码或验证码错误'
  35. return JsonResponse(res)
  36. l1 = len(username)
  37. if l1 > 10:
  38. res['message'] = '用户名长度不合法'
  39. return JsonResponse(res)
  40. # 对密码进行哈希存储
  41. pwd = hashlib.md5()
  42. pwd.update(password.encode())
  43. pwd_new = pwd.hexdigest()
  44. User.objects.create(username=username, email=email, password=pwd_new, career=career)
  45. request.session['username'] = username
  46. request.session['email'] = email
  47. res['status'] = 'success'
  48. res['message'] = '注册成功'
  49. return JsonResponse(res)

小结

对于这种有可能需要停留在原页面,保持原有状态的,前端一律采用Jquery能省很多事

因为常规的视图函数返回结果是HttpResponse或者HttpRedirectResponse

这种响应结果会直接渲染在html页面上,不符合我们的业务逻辑

视图函数中定义字典,字典类型可以在不报错的情况下转为JsonResponse

而在前端中拿到的响应结果必须是json数据(否则无法进行对data属性的调用),

换言之后端返回的响应体必须是JsonResponse,仅仅用json.dumps(res)还是不够,前端仍然无法调到正确响应结果

对于django中的路由

个人觉得,只要不影响的情况下,想省事一点,对于有访问不到的路由(末尾有无斜杠会导致各种错误的),可以把有斜杠和没有斜杠都写着,那样是最保险的写法,因为完全不需要django帮我们补全末尾斜杠(如果是django帮我们补全的话,访问的时候相当于重定向,如果此时还是post请求,那么会造成数据的丢失)所以在路由这块最好把两种形式都写上

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/224288?site
推荐阅读
相关标签
  

闽ICP备14008679号