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"的错误。
其他待修复问题
- GET请求不需要设置
contentType头,jQuery会自动处理JSON响应并解析为对象,无需手动JSON.parse。 - 序列化后的影院数据没有
fields层级,直接访问字段名即可(比如cinema.city),不需要cinema.fields.xxx。 - HTML模板中卡片div的
style属性未闭合引号,会导致渲染异常。 - 冗余代码
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
相关产品推荐
相关产品推荐

