利用 AJAX 和 javascript 使用 Django 消息传递框架创建 Toast



我遵循了一个教程,在尝试提交之前使用AJAX来验证输入字段。我让它在我的django建筑工地上工作;然而,我一直在使用toast提醒用户注意其他操作,不想偏离这一点。

$("#id_hub_name").focusout(function (e) {
e.preventDefault();
// get the hubname
var hub_name = $(this).val();
// GET AJAX request
$.ajax({
type: 'GET',
url: "{% url 'validate_hubname' %}",
data: {"hub_name": hub_name},
success: function (response) {
// if not valid user, alert the user
if(!response["valid"]){
alert("You cannot create a hub with same hub name");
var hubName = $("#id_hub_name");
hubName.val("")
hubName.focus()
}
},
error: function (response) {
console.log(response)
}
})
})

这是我目前的JS,我想把alert函数改为使用toast。

在我的base.html中,我使用以下内容来收听祝酒词并创建它们。

{% if messages %}
<div class="message-container">
{% for message in messages %}
{% with message.level as level %}
{% if level == 40 %}
{% include 'includes/toasts/toast_error.html' %}
{% elif level == 30 %}
{% include 'includes/toasts/toast_warning.html' %}
{% elif level == 25 %}
{% include 'includes/toasts/toast_success.html' %}
{% else %}
{% include 'includes/toasts/toast_info.html' %}
{% endif %}
{% endwith %}
{% endfor %}
</div>
{% endif %}

提前感谢

您只需要为toast追加html元素。

首先,松开{% if messages %},确保<div class="message-container">始终存在于模板中。如果没有消息,它将只是一个空的div。您还需要在js中添加toast的模板,这样您就可以添加来自js的toast。

现在,您只需在ajax响应之后附加toast的模板即可。

类似于:

function show_alert_from_js(alert_type, text) {
msg = `<<your template here>>${text}`;  // to render the text message to show.
msg_html = $.parseHTML(msg);
$('.message-container').append(msg_html);
}
$.ajax({
type: 'GET',
...
success: function (response) {
if(!response["valid"]){
show_alert_from_js("error", "You cannot create a hub with same hub name")
...
})

最新更新