【问题标题】:returned json response is undefended django返回的 json 响应是 undefended django
【发布时间】:2026-01-05 19:40:02
【问题描述】:

我正在尝试将我的 json 响应加载到我的模板中,但是当我将其检入控制台时返回 undefended

@login_required
def booking_detail_lists(request,id):
    obj = get_object_or_404(Booking.objects.annotate(no_persons=Count('takes_by')),id=id)
    bookingvisitors = BookingVisitor.objects.filter(booking=obj) 
    doc = Document.objects.filter(booking=obj)
    documents = []
    for i in doc:
        documents.append({
            'source':i.docs.url
        })
    visitors = []
    for i in bookingvisitors:
        visitors.append({
           'full_name':i.visitor.full_name,
           'reason':i.reason,
           'check_in_vis':i.check_in_vis.strftime("%Y-%m-%dT%H:%M"),
           'check_out_vis':i.check_out_vis.strftime("%Y-%m-%dT%H:%M"),
           'admin':i.admin.username,
           'date':i.date.strftime("%Y-%m-%dT%H:%M")
    })
    data = {
        'check_in':obj.check_in.strftime("%Y-%m-%dT%H:%M"),
        'check_out':obj.check_out.strftime("%Y-%m-%dT%H:%M"),
        'taker':obj.taker,
        'phone':obj.phone,
        'no_person':obj.no_persons,
        'id':obj.id,
        'takes_by':visitors,
        'images':documents,
    } 
    json_data = json.dumps(data)

    return render(request,'booking/booking_detail.html',{'data':json_data,'obj':obj,'id':obj.id})  

urls.py

path('ajax/booking/<int:id>',booking_detail_lists , name='booking_detail_lists'),

我的 html 模板和 ajax

$.ajax({
    type:'GET',
    url:"{%url 'booking:booking_detail_lists' id=2222 %}".replace(/2222/,parseInt({{id}})),
        success:function(data){
            console.log(data.data)

        }
    })
&lt;!--some html tags--&gt;

但是在浏览器控制台中返回undefined但是当我输入 {{data}} 时它会按我的预期显示?!谢谢你的推荐..

【问题讨论】:

    标签: javascript json django jsonresponse


    【解决方案1】:

    在函数booking_detail_lists 中,您将返回render('&lt;template_name&gt;', {&lt;Data for rendering in the template&gt;})...

    当您使用 ajax 调用此 URL 时,实际上返回了模板 booking_detail.html,它不是 json 格式,而是 html 格式。并且此响应没有属性 data(您'正在用data.data 打电话)..

    JsonResponse

    对于来自 django 视图的 json 响应,您需要使用来自 django.httpJsonResponse

    • 更改您的函数以包含此
      # ...Rest Imports
      from django.http import JsonResponse
      
      @login_required
      def booking_detail_lists(request, id):
      
        # ...Processing and generation of data
      
        return JsonResponse({'data':json_data,'obj':obj,'id':obj.id})
      

    【讨论】:

      最近更新 更多