我遇到了 ajax toastr 的问题,我也在使用 bootstrap 5,所以这可能会导致样式问题。
我的阿贾克斯:
{% load humanize %}
{% load static %}
<link rel="stylesheet" href="{% static 'style.css' %}">
<link href="toastr.css" rel="stylesheet"/>
{% block extra_js %}
<script src="toastr.js"></script>
<script src="https://code.jquery.com/jquery-3.5.1.js"
integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
crossorigin="anonymous"></script>
<script type="text/javascript">
let csrftoken = '{{ csrf_token }}'
$(document).on('submit','#add-to-favourite',function(e){
e.preventDefault();
$.ajax({
type: $(this).attr('method'),
headers:{'X-CSRFToken':csrftoken},
url: $(this).attr('action'),
data: $(this).serialize(),
success: function (response) {
alert("Succes");
toastr.options.closeButton = true;
toastr.success('Added to Favourite');
}
})
});
</script>
{% endblock extra_js %}
警报消息显示正常,ajax 函数返回成功。
导入Jquery后必须导入lib toastr,因为Jquery是toastr的依赖。
就放
<script src="toastr.js"></script>
之后
<script src="https://code.jquery.com/jquery-3.5.1.js"
integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
crossorigin="anonymous"></script>
像这样:
{% load humanize %}
{% load static %}
<link rel="stylesheet" href="{% static 'style.css' %}">
<link href="toastr.css" rel="stylesheet"/>
{% block extra_js %}
<script src="https://code.jquery.com/jquery-3.5.1.js"
integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
crossorigin="anonymous"></script>
<script src="toastr.js"></script>
<script type="text/javascript">
let csrftoken = '{{ csrf_token }}'
$(document).on('submit','#add-to-favourite',function(e){
e.preventDefault();
$.ajax({
type: $(this).attr('method'),
headers:{'X-CSRFToken':csrftoken},
url: $(this).attr('action'),
data: $(this).serialize(),
success: function (response) {
alert("Succes");
toastr.options.closeButton = true;
toastr.success('Added to Favourite');
}
})
});
</script>
{% endblock extra_js %}