萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Django AJAX 請求回傳 JSON:驗證 Email 是否已註冊

後端 View


from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.models import User
import json

@csrf_exempt  # 示範用,生產請用 csrf_token
def check_email(request):
    if request.method != 'POST':
        return JsonResponse({'error': 'POST only'}, status=405)

    email = request.POST.get('email', '').strip()
    if not email:
        return JsonResponse({'exists': False})

    exists = User.objects.filter(email__iexact=email).exists()
    return JsonResponse({'exists': exists})

URL 設定


# urls.py
path('api/check-email/', views.check_email, name='check_email')

前端 jQuery AJAX


$('#email').on('blur', function() {
    var email = $(this).val();
    if (!email) return;

    $.post('/api/check-email/', {email: email}, function(res) {
        if (res.exists) {
            $('#email-msg').text('此 Email 已註冊').addClass('error');
            $('#submit-btn').prop('disabled', true);
        } else {
            $('#email-msg').text('可使用').removeClass('error');
            $('#submit-btn').prop('disabled', false);
        }
    }, 'json');
});

進階:Django REST Framework (DRF) 寫法


from rest_framework.decorators import api_view
from rest_framework.response import Response

@api_view(['POST'])
def check_email_drf(request):
    email = request.data.get('email', '')
    exists = User.objects.filter(email__iexact=email).exists()
    return Response({'exists': exists})

安全建議

  • 生產環境**必須**啟用 CSRF 保護(@ensure_csrf_cookie + 前端攜帶 X-CSRFToken)
  • 限制請求頻率(django-ratelimit 或 DRF Throttling)
  • Email 存在性洩露風險:考慮統一回傳「若帳號存在將寄送重設信」訊息

總結

Django 回傳 JSON 極簡單:JsonResponse 或 DRF Response。前端 $.post/fetch 配合即時驗證,提升使用者體驗。

copyright © 萬盛學電腦網 all rights reserved