Ajax URL 未执行 views.py 中定义的正确函数 urls.py

Ajax URL Not Executing The Correct Function in views.py As Defined in urls.py

我正在利用 Ajax 制作一些饼图,但 data-ajax-url 没有按预期(或我想的那样)工作。根据 urls.py,reptibase:item-update 应该在我的 views.py 文件中执行 item_update 函数。 item_update 永远不会执行,而是再次执行与当前页面关联的相同功能 url。

目前,我收到一个解析错误,因为 HTML 而不是 json。 json 是从我的 item_update 函数返回的。

item.js

window.onload = function () {
        console.log("Child: ", document.getElementById("piee"))
        var ctx = document.getElementById("piee").getContext('2d');

        var rep_name = $("#pie1").attr("data-rep-name")
        var ajax_url = $("#pie1").attr('data-ajax-url')
        var _data = []
        var _labels = []

        // Using the core $.ajax() method
        $.ajax({

            // The URL for the request
            url: ajax_url,

            // The data to send (will be converted to a query string)
            data: {
                name: rep_name
            },

            // Whether this is a POST or GET request
            type: "POST",

            // The type of data we expect back
            dataType: "json",

            headers: {'X-CSRFToken': csrftoken},

            context: this
        })
            // Code to run if the request succeeds (is done);
            // The response is passed to the function
            .done(function (json) {

                if (json.success == 'success') {
                    var newMale = json.malePerc
                    var newFemale = json.femalePerc
                    console.log(newMale, newFemale)
                    _labels.push("male", "female")
                    _data.push(parseFloat(newMale), parseFloat(newFemale))
                    window.myPie.update()
                    var newUVB = json.uvbPerc
                    var newSize = json.specSize

                } else {
                    alert("Error: " + json.error);
                }
            })
            // Code to run if the request fails; the raw request and
            // status codes are passed to the function
            .fail(function (xhr, status, errorThrown) {
                alert("Sorry, there was a problem!");
                console.log("Error: " + errorThrown);
                console.log("Status: " + status);
                console.dir(xhr);
                console.warn(xhr.responseText)
            })
            // Code to run regardless of success or failure;
            .always(function (xhr, status) {
                //alert("The request is complete!");
            });

        var config = {
            type: 'pie',
            data: {
                datasets: [{
                    data: _data,
                    backgroundColor: ['#ff0000', "#0000ff"],
                    label: "Temp"
                }],
                labels: _labels,
            },
            options: {
                responsive: true
            }
        };

        console.log("data", _data);
        console.log("config", config)
        window.myPie = new Chart(ctx, config);
        console.log("window", window.myPie)
    }

urls.py

app_name = 'reptibase'
urlpatterns = [
    path('', views.index, name='home'),
    path('search', views.reptile_search, name='search'),
    path('add', views.reptile_add, name='add'),
    path('list', views.reptile_list, name='list'),
    path('listD', views.reptile_listDelete, name='listDelete'),
    #path('<int:rep_id>', views.reptile_item, name='item'),
    path('<str:scientific>', views.reptile_itemAlt, name='itemAlt'),
    path('<int:rep_id>,<int:specific_id>', views.reptile_itemAlt_Edit, name='itemAltEdit'),
    path('<str:reptile>,<int:id>', views.comments, name='comments'),
    path('update', views.item_update, name='item-update'),
    path('edit', views.reptile_edit, name='edit'),
]

itemAlt.html

<div class="pie-chart" id="pie1" data-rep-name="{{ reptile.scientific }}"
     data-ajax-url="{% url "reptibase:item-update" %}">
    <canvas id="piee"></canvas>
    <div class="graph-popout">
        <div class="data">
            <p>{{ femalePerc }}% Female, {{ malePerc }}% Male. {{ size }} Individuals</p>
        </div>
        <p><a href="#">Report Issue</a></p>
        <p><a href="#" class="share">Share</a></p>
    </div>
    <h3>Sex</h3>
    <div class="background"></div>
    <div id="slice1" class="pie-slice">
        <div class="pie"></div>
    </div>
    <div id="slice2" class="pie-slice">
        <div class="pie"></div>
    </div>
    <div id="slice3" class="pie-slice">
        <div class="pie"></div>
    </div>
</div>

path('<str:scientific>', views.reptile_itemAlt, name='itemAlt'),

可能会匹配您要前往的请求:

path('update', views.item_update, name='item-update'),

并扩展到下面的编辑端点!

将 'item-update'(reptibase/update) 和 'edit'(repitbase/edit) 移动到 'itemAlt' 上方以说明它们各自的路径,然后所有其他请求都应该通过通过这些并被正确的视图捕获。

请看这里'The Path Before Us'一节,很好的解释了这个现象:

https://www.mattlayman.com/understand-django/urls-lead-way/