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

Django无法渲染HTML页面仅返回JSON,需用Fetch填充表格

Django前端Fetch调用API时,访问/product/仅返回JSON无法渲染页面的解决方法

核心问题是当前路由product/<int:id>/只绑定了返回JSON的API视图,直接访问该路径会拿到JSON数据而非渲染后的HTML页面。要实现前端Fetch填充数据的需求,需拆分页面路由与API路由,同时修正前端代码错误。

解决方案步骤

1. 拆分路由与视图

在urls.py中新增页面路由,将API路由独立出来:

# urls.py
from django.urls import path
from . import views

urlpatterns = [
    # 页面路由:返回渲染好的getbyid.html
    path('product/<int:id>/', views.product_detail_page, name='product_detail_page'),
    # API路由:返回JSON数据
    path('api/product/<int:id>/', views.product_detail_api, name='product_detail_api'),
    # 其他现有路由...
]

2. 调整视图函数

  • 新增返回页面的视图(负责渲染HTML):
# views.py
from django.shortcuts import render
from django.contrib.auth.decorators import login_required

@login_required(login_url='login')
def product_detail_page(request, id):
    # 无需传递product数据,前端通过Fetch获取
    return render(request, 'getbyid.html')
  • 修改原API视图并改名,保留权限验证:
# views.py
from django.http import JsonResponse, HttpResponseNotFound
from .models import Product

@login_required(login_url='login')  # 必须加登录验证,避免未登录访问API
def product_detail_api(request, id):
    try:
        product = Product.objects.get(id=id, user=request.user)
        product_data = {
            'id': product.id,
            'Name': product.Name,
            'quantity': product.quantity,
            'price': product.price
        }
        return JsonResponse(product_data)
    except Product.DoesNotExist:
        return HttpResponseNotFound()

3. 修正前端Fetch代码

原前端代码存在两处关键错误,同时需调整API请求地址:

<!-- getbyid.html 中的script部分修正 -->
<script>
    fetchProductDetails();

    function fetchProductDetails() {
        const productId = getProductIdFromUrl();
        // 请求新的API路由
        fetch(`/api/product/${productId}`)
            .then(response => {
                // 处理登录重定向
                if (response.redirected) {
                    window.location.href = response.url;
                    return;
                }
                if (!response.ok) {
                    throw new Error(`请求失败:${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                // 直接填充页面中已有的td元素,避免重复行
                document.getElementById('product-id').textContent = data.id;
                document.getElementById('product-Name').textContent = data.Name;
                document.getElementById('product-quantity').textContent = data.quantity;
                document.getElementById('product-price').textContent = data.price;
            })
            .catch(error => {
                console.error('获取产品详情失败:', error);
            });
    }

    function getProductIdFromUrl() {
        // 用URL对象解析更可靠,避免路径结尾/的问题
        const url = new URL(window.location.href);
        const pathSegments = url.pathname.split('/').filter(seg => seg.length > 0);
        return pathSegments[pathSegments.length - 1];
    }
</script>

修正点说明:

  • 原代码中document.getElementById('productId')是错误的,表格id为products,且无需新增行,直接填充已有td即可
  • 改用URL对象解析路径,比字符串split更稳定
  • 新增登录重定向处理,避免未登录时Fetch拿到登录页面HTML导致解析错误

4. 测试验证

访问http://127.0.0.1:8000/product/9/,此时会渲染getbyid.html页面,前端自动调用/api/product/9/获取JSON数据并填充到表格中。


内容的提问来源于stack exchange,提问作者Shaik Shahid Afridi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 14:12:02