【问题标题】:Trying to render a python dictionary into django template with javascript尝试使用 javascript 将 python 字典呈现为 django 模板
【发布时间】:2020-07-20 14:03:04
【问题描述】:

我正在尝试使用 ajax 将 python 字典呈现到我的 django 模板中。我有一些来自 whoisLookup 的结果,我想在某些表格行中呈现这些结果。对 django 和 JavaScript 完全陌生!

我的views.py代码

def whois_lookup(request):
    if request.is_ajax():
        domain = request.session.get('domain_or_ip')
        res = whois.whois(domain)
        data = {'message': 'whois-lookup completed.',
                'domain_name': res.domain_name
                }
        return HttpResponse(json.dumps(data), content_type='application/json')
    else:
        raise Http404

我在 .js 文件中尝试了什么。

$(document).ready(function () {
$('#whois-btn').click(function () {
    $.ajax({
        type: "GET",
        url: "/WanDashboard/whoisLookup/",
        beforeSend: () => {
            $(".ajax_loader").show();
            console.log('BeforeSend whoisLookup');
        },
        success: function (data) {
            # this works.
            alert(data.message);
            # this does not work
            alert(data.domain_name)
        },
        complete: () => {
            $(".ajax_loader").hide();
            console.log('Completed whois ajax request.');
        }
    });
});

});

.html 页面

<div id="whois-results">
<table class="table table-dark" id="result_whois_table">
    <thead>
    <tr>
        <th scope="col">Domain Name</th>
        <th scope="col">Whois Server</th>
        <th scope="col">Name Servers</th>
        <th scope="col">Contact mails</th>
        <th scope="col">Address</th>
        <th scope="col">City</th>
    </tr>
    </thead>
    <tbody>
    <tr>
        <td>{{ data.domain_name }}</td>
    </tr>
    </tbody>
</table>

【问题讨论】:

  • 你没有在任何地方使用 django 模板。
  • 对不起,我编辑了帖子
  • 在到达客户端之前,您需要了解 HTML 是在服务器端使用 django 模板呈现的。在您看来,您给出的 JSON 响应不涉及任何 Django 模板。
  • 您尝试做的是直接从 Django 提供 HTML(这完全可以),但随后您尝试将其用作 API。我认为你真正需要的是 Django-REST 框架...

标签: python django ajax


【解决方案1】:
domain = request.session.get('domain_or_ip')

我不确定您在此处添加的代码是否与您的应用程序中的完全相同 - 但 .get() 需要一个有效参数。例如

domain = request.session.get('https://api.github.com/user')

您的 whois_lookup 函数会将 JSON 转储返回到您在 urls.py 文件中分配给它的 url。

因此,您的模板将无法工作,因为它们没有像 @vishal 在 cmets 中提到的那样设置。

【讨论】:

    【解决方案2】:

    有点晚了,但我设法做到了。

    views.py 代码

    def whois_lookup(request):
    if request.is_ajax():
        domain = request.session.get('domain_or_ip')
        res = whois.whois(domain)
        l_nameservers = res.name_servers
            nameservers = ' '.join([str(elem) for elem in l_nameservers])
        whois_data = {
            'message': 'Completed-scan!',
            'nameservers': nameservers
        }
        return JsonResponse(whois_data, safe=False)
    else:
        raise Http404
    

    以及帮助我​​完成这项工作的 JavaScript 代码。

    $(document).ready(function () {
    $('#whois-btn').click(function () {
        $.ajax({
            type: "GET",
            url: "/WanDashboard/whoisLookup/",
            dataType: 'json',
            beforeSend: () => {
                $(".ajax_loader").show();
                console.log('BeforeSend whoisLookup');
            },
            success: function (whois_data) {
                let splitted_array_nameservers = whois_data.nameservers.split("");
                $("#result_whois_table").show();
                let whois_table = $("#result_whois_table tbody");
                whois_table.append("<tr><td>" + whois_data.nameservers + "</td></tr>")
            },
            complete: () => {
                $(".ajax_loader").hide();
                console.log('Completed ajax.');
            }
        });
    });
    

    });

    不过,这是一个非常粗略的解决方案!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-11
      • 2018-11-09
      • 2018-10-22
      • 2011-07-12
      • 1970-01-01
      • 1970-01-01
      • 2017-03-28
      • 1970-01-01
      相关资源
      最近更新 更多