python - 如何从同一个 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)”下划线。请告诉我我该怎么做。提前致谢!
解决方案
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
}
推荐阅读
- javascript - 在 Nodejs 中设置 cookie
- reactjs - 反应:构建不完整
- gtk - 配置错误,在带有 Homebrew 的 Mac OS X Mojave 上找不到 X 或 gtk-config
- laravel - 我们可以在 Laravel 中使用 PUT 方法进行文件上传吗?
- javascript - 通过动态函数从方法对象执行成功的ajax
- python - 使用 altair 在 jupyterlab 中注册自定义 vega 格式化程序
- ruby-on-rails - Rails:PATCH请求未进入控制器方法
- python - 为什么在某些 Python 函数中可以省略 return 关键字?
- html - 中心计数器引导模式
- javascript - Web MediaRecorder - 将数据缓慢上传到服务器