如何从同一个Python函数中获得不同的返回?

2024-10-01 11:33:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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)
}

例如,我希望将“Correct!”消息设为绿色,而如果它返回“Correct…”,我希望它变为红色,并在回答“str(coreng)”下面划线。请告诉我怎么做。提前谢谢


Tags: divformidmessageinputgettyperandom
1条回答
网友
1楼 · 发布于 2024-10-01 11:33:38
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
}

相关问题 更多 >