简体   繁体   English

从ajax添加Django视图结果作为模板中的表

[英]Adding django view result from ajax as table in template

I have a django model and I view i am aggregating few columns and filtering result and returning as below 我有一个Django模型,我认为我正在汇总几列并过滤结果,并返回如下

def show_grid_summery(request):
    id = request.GET.get('id', None)

    context = {
        "summery": [],
    }

    result = Records.objects.filter(grid_id_id = id).aggregate(Sum('house_count'), Sum('point_count'))
    if len(result) != 0:
        context["summery"].append([result['house_count__sum'], result['point_count__sum']])


    return JsonResponse(context)

And on the template i am getting results using ajax 在模板上,我正在使用ajax获得结果

$.ajax({
                    url: 'ajax/summery/',

                    data: {
                      'id': ID
                    },

                    dataType: 'json',

                    success: function (data) {
                        alert(data);

                        var trHTML = '';
                        document.getElementById('summaryLabel').innerHTML = '';

                        $.each(data.summery , function (item) {
                            trHTML += '<tr><td>' + item[0] + '</td><td>' + item[1] + '</td></tr>';
                        });
                        $('#summaryLabel').append(trHTML);
                    }

Now I want to fill the results record (2 columns) as a table inside the #summaryLabel tag. 现在,我想将结果记录(2列)填充为#summaryLabel标记内的表格。 (preferably with headers as well). (最好还有标题)。 But I am unable to sort it out after many different attempts. 但经过许多不同的尝试,我无法对其进行分类。

html part is html部分是

<table id="summaryLabel">
            <p>information.</p>
</table>

The jQuery $.each() function passes two parameters, the first is the array index, the second is the object. jQuery $.each()函数传递两个参数,第一个是数组索引,第二个是对象。 So it would seem that in your code, your item variable would contain the index, which is not what you want. 因此,似乎在您的代码中,您的item变量将包含索引,而这不是您想要的。

Try: 尝试:

$.each(data['summery'] , function (i, item) {
    trHTML += '<tr><td>' + item[0] + '</td><td>' + item[1] + '</td></tr>';
});

or just 要不就

$.each(data['summery'] , function () {
    trHTML += '<tr><td>' + this[0] + '</td><td>' + this[1] + '</td></tr>';
});

jQuery $.each() is documented here: http://api.jquery.com/jquery.each/ 此处记录了jQuery $.each()http$.each()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM