【发布时间】: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 框架...