首页 > 解决方案 > 如何从同一个 Python 函数中获得 CSS 样式的不同返回值?

问题描述

我有一个 Python 函数,它在不同的场景中返回不同的消息。我想以不同的方式设置不同的消息样式,但我不知道该怎么做。这是我的功能:

def checkans(request, spanish_id):
    random_spanish_question = get_object_or_404(Spanish, pk=spanish_id)
    query = request.GET.get('ans')
    coreng = random_spanish_question.english_set.get()
    if query == str(coreng):
        message = {
        'message' : "Correct!"
        } 
        return JsonResponse(message)
    else:
        message = { 
        'message' : "Incorrect. The correct answer is " + str(coreng)
        }
        return JsonResponse(message)

这是 HTML 页面:

<div class="flexcontainer" style="justify-content: center;">
    <div class="sectiontitle">Quiz time
    </div>
        <div class="question_card">
            <div class="question_word">{{ random_spanish_question }}</div>
            <div id="msg"></div>
            <form action="/checkans/{{random_spanish_question.id}}/" method="get">{% csrf_token %}
                <label for="ans">Answer:</label>
                <input type="text" name="ans"autofocus autocomplete="off" id="ansfield"/>
                <input type="submit" value="Submit"/ id="submitbtn">
            </form>
        <input type="submit" value="Skip"/>
        <button onclick="location.reload();">Next</button>
        </div>
</div>

这是 JS 和 AJAX 代码:

$('form').on('submit', function(e){
    e.preventDefault();

    var form = $(this);
    var url = form.attr('action');

    $.ajax({
        type: 'GET',
        url: url,
        data: form.serialize(),
        success: function(data){
            $("#msg").html(data.message);
        }
    });

    disable();
})

function disable(e){
    $('#submitbtn').prop('disabled', true);
    $('#ansfield').prop('disabled', true)
}

例如,我想做“正确!” 消息绿色,而如果它返回“不正确...”,我希望它是红色的,并在答案“str(coreng)”下划线。请告诉我我该怎么做。提前致谢!

标签: pythonhtmlcssdjangoajax

解决方案


def checkans(request, spanish_id):
    random_spanish_question = get_object_or_404(Spanish, pk=spanish_id)
    query = request.GET.get('ans')
    coreng = random_spanish_question.english_set.get()
    if query == str(coreng):
        message = {
            'message' : "<span class=\"result-correct\">Correct!</span>"
        } 
    return JsonResponse(message)
    else:
    message = { =
        'message' : "<span class=\"result-incorrect\">Incorrect. The correct answer is " + str(coreng)</span>
    }
return JsonResponse(message)

这些类在css中定义:

.result-correct{
    color:#00aa00; // or any shade of green you like
}

.result-incorrect{
    color:#aa0000; // or any shade of red you like
}

推荐阅读