You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django项目导航栏分类按钮点击无响应问题求助

解决Django分类按钮点击无反应问题

按以下步骤逐一排查并修复问题:

1. 处理Fetch请求响应,更新页面内容

当前JavaScript仅发送了POST请求,但未处理视图返回的HTML响应,导致页面无变化。修改exploringCategory函数,添加响应处理逻辑:

function exploringCategory(category) {
    var url = 'category_exploring/'
    fetch(url,{
        method:'POST',
        headers:{
            'Content-Type' : 'application/json',
            'X-CSRFToken': csrftoken,
        },
        body:JSON.stringify({'category' : category})
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('请求失败');
        }
        return response.text();
    })
    .then(html => {
        // 假设商品列表容器的id为product-container,替换其内容
        document.getElementById('product-container').innerHTML = html;
        // 若需刷新整个页面,可替换为:window.location.reload();
    })
    .catch(error => {
        console.error('请求出错:', error);
    });
}

2. 确保CSRF Token变量正确定义

检查模板中是否正确获取CSRF Token,否则csrftoken变量会未定义导致请求失败。在模板的<script>开头添加:

<script>
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    const csrftoken = getCookie('csrftoken');
    // 原有JS代码...
</script>

3. 使用绝对URL避免路径错误

相对路径'category_exploring/'可能因当前页面URL层级问题导致404,建议用Django的{% url %}标签生成正确URL:

// 模板中替换url变量
var url = "{% url 'category_exploring' %}";

需先在URL配置中给视图命名:

# urls.py
path('category_exploring/', views.category_exploring, name='category_exploring'),

4. 处理未登录用户的异常

视图中Order.objects.get_or_create(customer=user)在用户未登录时(request.user为匿名用户)会报错,需添加登录判断:

from django.contrib.auth.decorators import login_required

@login_required(login_url='/login/')  # 未登录则重定向到登录页
def category_exploring(request):
    data = json.loads(request.body)
    category = data['category']
    user = request.user
    products = Product.objects.filter(category=category)
    order, created = Order.objects.get_or_create(customer = user, complete = False)
    cartItems = order.get_total_order_cnt
    context = {'products' : products, 'cartItems': cartItems}
    return render(request, 'store/store.html', context)

若允许未登录用户浏览,需调整Order模型的customer字段为可选,或用session处理匿名用户购物车。

5. 检查浏览器控制台错误

按F12打开开发者工具,切换到Console标签,查看是否有JS变量未定义、请求404/500等错误,这是快速定位问题的关键。

内容的提问来源于stack exchange,提问作者Lina Alrashid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 04:46:20