{% extends 'base.html' %}
{% block tittle %}登陆{% endblock tittle %}
{% block body %}
    <h1>登陆</h1>
    <form id="loginForm" onsubmit="event.preventDefault(); submitForm();">
        {% csrf_token %}
        <label for="username">用户名:</label>
        <input type="text" id="username" name="username" required><br>
        <label for="password">密码:</label>
        <input type="password" id="password" name="password" required><br>
        <button type="submit">登陆</button>
        <a href="/exam/register">注册</a>
    </form>

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

{% block script %}
        <script>
        function submitForm() {
            $.ajax({
                url: "{% url 'exam:login' %}", // Django模板标签，用于生成URL
                type: "POST",
                data: $('#loginForm').serialize(),
                success: function(response) {
                    if (response.code === 200) {
                        alert(response.message); // 成功时的消息框
                        window.location.href = "/exam";
                    } else {
                        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 %}