简体   繁体   English

当前路径具有子目录或url参数时,使用AJAX调用视图函数不起作用(Django)

[英]Calling a view function with AJAX not working when current path has sub directory or url parameter (Django)

I am using AJAX to call a view function when my pages load to return a count value (no. of items in basket). 当页面加载返回计数值(购物篮中的项目数)时,我正在使用AJAX调用视图函数。 This works fine for most of my url paths but when the current path has a sub directory or url parameter value I get a 404 error. 这对于我的大多数url路径都适用,但是当当前路径具有子目录或url参数值时,我会收到404错误。

Below are a some of my url patterns. 以下是我的一些网址格式。 The bottom one is the view function I call to return the count value. 最底层的是我调用的视图函数以返回计数值。 When I visit the 'orders' path the basket count is returned successfully but for the 'order_history' and 'view_order' paths I get the 404, eg 'Not Found: /view_order/basket_count' 当我访问“订单”路径时,已成功返回购物篮计数,但对于“ order_history”和“ view_order”路径,我得到了404,例如“未找到:/ view_order / basket_count”

path("my_orders", views.orders, name="orders"),
path("my_orders/history", views.order_history, name="order_history"),
path("view_order/<int:id>", views.view_order, name="view_order"),
path("basket_count", views.basket_count, name="basket_count"), 

Very new to Python/Django so I'm sure I'm not grasping something very fundamental here and the url patterns are not resolving correctly. Python / Django的新手,所以我确定我在这里没有掌握非常基本的内容,并且url模式无法正确解析。 I previously had the basket_count in another file called utils.py and referenced it with utils.basket_count which gives the same outcome. 我以前在另一个名为utils.py的文件中使用了basket_count,并使用utils.basket_count对其进行了引用,该结果相同。 I suppose I could just call the function within each of my views but my intention here was to experiment with AJAX. 我想我可以在每个视图中调用该函数,但是我的目的是尝试使用AJAX。 Is there a simple change to my url patterns that will fix this issue with my current setup or is it simply bad practice? 是否对我的网址格式进行了简单的更改以解决当前设置中的此问题,或者只是一种不好的做法?

My AJAX code 我的AJAX代码

document.addEventListener('DOMContentLoaded', function() {
  var basket_count = new XMLHttpRequest();
  basket_count.open('GET', '/basket_count/', true);
  basket_count.send();

  basket_count.onload = function() {

    var count = JSON.parse(basket_count.responseText);
    if (count.count > 0) {
        document.getElementById('nav_basket_count').innerHTML = ' [' + count.count + ']';
    } else {
        document.getElementById('nav_basket_count').innerHTML = '';
    }
  };
});

The problem was with my AJAX code. 问题出在我的AJAX代码上。 I had a trailing forward slash in the url when there should just have been one at the start, as shown below. 当刚开始时应该有一个斜杠时,URL中会有一个正斜杠,如下所示。

basket_count.open('GET', '/basket_count', true);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM