{% extends 'base.html' %}
{% block tittle %}注册页面{% endblock tittle %}
{% block body %}
    <h1>注册</h1>
    <form id="registerForm" onsubmit="event.preventDefault(); submitForm();">
        {% csrf_token %}
        <label for="username">用户名:</label>
        <input type="text" id="username" name="username" required><br>
        <label for="nickname">昵称:</label>
        <input type="text" id="nickname" name="nickname" required><br>
        <label for="password1">密码:</label>
        <input type="password" id="password1" name="password1" required><br>
        <label for="password2">确认密码:</label>
        <input type="password" id="password2" name="password2" required><br>
        <label for="email">邮箱:</label>
        <input type="email" id="email" name="email" required><br>
        <button type="submit">Register</button>
    </form>

    <!-- 错误信息显示区域 -->
    <div id="errorMessage" style="display: none;"></div>
{% endblock body %}

{% block script %}
        <script>
        function submitForm() {
            $.ajax({
                url: "{% url 'exam:register' %}", // Django模板标签，用于生成URL
                type: "POST",
                data: $('#registerForm').serialize(),
                success: function(response) {
                    if (response.code === 200) {
                        alert(response.message); // 成功时的消息框
                    } else {
                        displayErrors(response.data); // 显示错误信息
                        alert(response.message);
                    }
                },
                error: function() {
                    alert("An error occurred while processing your request.");
                }
            });
        }

        function displayErrors(errors) {
            $('#errorMessage').html('');
            for (let key in errors) {
                if (errors.hasOwnProperty(key)) {
                    let message = errors[key];
                    $('#errorMessage').append('<p>' + message + '</p>');
                }
            }
            $('#errorMessage').show();
        }
    </script>
{% endblock script %}