【问题标题】:How to print Django Ajax return as Template Data?如何将 Django Ajax 返回作为模板数据打印?
【发布时间】:2022-01-23 19:20:26
【问题描述】:

我想打印模板上以下视图返回的Products 数据。当我检查上下文时,它打印了正确的数据,但是当我尝试在模板中打印数据时,它什么也没显示。我在浏览器控制台中检查了网络,那里调用了数据,但我不知道为什么它不打印到视图

模板

 {% for product in products%}
                    {{product.name}}
                    {%endfor%}

我的阿贾克斯:

$(document).ready(function() {
    var compare = localStorage.getItem("comparisionItems");
    var compareObj = JSON.parse(compare);
    
    
    
    console.log(compareObj)
    
   
      
    $.ajax({
      url: './compare',
      type: "POST",
      data: compare,
      headers: { "X-CSRFToken": $.cookie("csrftoken") },
      dataType: "json",
      contentType : "application/json",
      processData: "false",
      success: function (data) {
        location.reload();
          
       },
      
    });
});

Views.py

def compare(request):
    is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest'
    if is_ajax and request.method == "POST":             
        data = json.loads(request.body)     
        compare_ids = data['itemIds']      
        products = Products.objects.filter(id__in=compare_ids)   
        print(products)   
        context={'products':products}
        return render(request,'./compare.html', context)
    else:
     return render(request,'./compare.html')

【问题讨论】:

    标签: jquery django ajax django-views django-templates


    【解决方案1】:

    QuerySet 是惰性的!

    当您在浏览器控制台中调用 print() 函数或 log() 函数时,产品查询集将立即评估

    您可以使用 all() 以便它在您的模板中进行评估:

    products = Products.objects.filter(id__in=compare_ids).all()

    也看看这个documentions


    服务器端:

    因为你不打数据库,所以使用GET方法:

    在views.py中

    from django.views.decorators.http import require_GET
    
    @required_GET
    def compare(request):
        is_ajax = request.headers.get('X-Requested-With') =='XMLHttpRequest'
        if is_ajax:             
            compare_ids = request.GET.get('itemIds')          
            products = Products.objects.filter(id__in=compare_ids).all()     
            context={'products':products}
            return render(request,'./compare.html', context)
        else:
         return render(request,'./compare.html')
    

    客户端:

    你应该替换html也不重新加载

    $.ajax({
          url: './compare',
          type: 'GET',
          data: compare,
          success: function (data) {
            console.log(data);
            $('your_list_selector').html(data);
           },
          
        });
    

    【讨论】:

    • 我在浏览器控制台中检查了网络,那里调用了数据并且控制台打印正确,所以这不是这里的问题。
    • 哦,我认为你应该使用其他成功功能而不是重新加载,因为它会重置你的模板,而且如果你不点击数据库,你不需要使用 post 方法,最好使用 get 方法跨度>
    • 它命中数据库,因为我需要打印 id 等于 localstorage 项目 id 的数据库对象。我正在获取数据,但它仅在网络控制台上打印,我假设当页面加载时它会加载 get 请求并且 Ajax 是通过 post 传递的。现在帖子数据没有纠正。
    • 我更新了我的答案,你试试吗?你删除 location.reload 吗?
    • 我的英文不好,我的意思是你正在从数据库中读取数据而不是写入它,所以你不需要POST方法
    猜你喜欢
    • 2013-01-21
    • 2011-02-02
    • 1970-01-01
    • 2012-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    相关资源
    最近更新 更多