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

AJAX请求Django接口报JSON语法错误,无法渲染影院数据

解决AJAX请求JSON解析错误及影院数据展示问题

核心错误原因

你在AJAX的success回调里执行JSON.parse(response.cinemas)时触发了语法错误,因为:

  • Django REST Framework的ListAPIView返回的直接是影院对象的数组,response本身就是这个数组,response.cinemas是undefined,对undefined执行JSON.parse()自然会抛出"undefined is not valid JSON"的错误。

其他待修复问题

  1. GET请求不需要设置contentType头,jQuery会自动处理JSON响应并解析为对象,无需手动JSON.parse。
  2. 序列化后的影院数据没有fields层级,直接访问字段名即可(比如cinema.city),不需要cinema.fields.xxx。
  3. HTML模板中卡片div的style属性未闭合引号,会导致渲染异常。
  4. 冗余代码var cinemaName = cinema.fields.all;无意义且会报错,需删除。

修改后的代码

main.js

$(document).ready(() => {
    $("[id^='cinema']").click((event) => {
        var cityID = event.target.getAttribute('data-city-id');

        $.ajax({
            url: `http://localhost:8000/myapp/get_theatre_by_city_id?city_id=${cityID}`,
            method: 'GET',
            headers: {
                "x-csrf-token": $("input[name='csrfmiddlewaretoken']").val()
            },
            success: (response) => {
                $("#result").html('');
                response.forEach(cinema => {
                    $("#result").append(`
                        <div style="float: left; margin: 0 10px 10px 0;">
                            <div class="card" style="width: 18rem;">
                                <a href="#">
                                    <img class="img-top-fluid"
                                        src="${cinema.image}"
                                        alt="${cinema.cinema}">
                                </a>
                                <div class="card-body">
                                    <h4 class="card-title">
                                        <a href="/myapp/${cinema.url}">${cinema.cinema}</a>
                                    </h4>
                                    <h5>${cinema.city}</h5>
                                    <p class="card-text">${cinema.address}</p>
                                </div>
                            </div>
                        </div>
                    `);
                });
            },
            error: (xhr, status, error) => {
                console.error("加载错误:", status, error);
                alert("加载影院数据失败");
            }
        });
    });
});

views.py(优化异常处理)

class CinemasListView(generics.ListAPIView):
    serializer_class = CinemaSerializer

    def get_queryset(self):
        try:
            city = CityLocation.objects.get(pk=self.request.GET.get('city_id'))
            return Cinema.objects.filter(city=city)
        except CityLocation.DoesNotExist:
            return Cinema.objects.none()

关键修改说明

  • 直接使用response作为影院数组,无需手动解析JSON。
  • 修正字段访问方式,匹配序列化器返回的扁平数据结构。
  • 修复HTML语法错误,添加卡片间距提升视觉效果。
  • 增加错误回调的日志打印,方便调试问题。
  • 后端添加异常处理,避免无效city_id导致服务器崩溃。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 23:42:11