Django Ajax toastr成功时不显示

plicqrtu  于 2023-10-21  发布在  Go
关注(0)|答案(1)|浏览(143)

我遇到了一个问题,我用的是bootstrap 5,所以可能会导致风格问题。
我的Ajax:

{% 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 %}

警报消息显示OK,因此警报功能返回成功。

2jcobegt

2jcobegt1#

库toastr的导入必须在导入Jquery之后完成,因为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 %}

相关问题