先在后台处理要发送的数据:
def ajax_server(request):
# 把要查询的字段以这种方式放入下面的类表中,
# 如果要查那个字段,就将此字段显示,否则则注销,
table_config = [
{
"field":'id', # 数据库中的字段
"title":'id', # 在前端页面展示的字段名称
},
{
"field":'hostname',
"title":'主机名'
},
{
"field":'sn',
"title":'sn号'
}
]
filed_list = []
for v in table_config:
filed_list.append(v['field'])
server_list = models.Server.objects.values(*filed_list)
print(server_list)
total = models.Server.objects.count()
ret = {
'total':total,
'rows':list(server_list)
}
print(ret)
return JsonResponse(ret,safe=False)
前端数据渲染:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h2>资产列表管理</h2>
<table border="1px">
<thead id="thead">
</thead>
<tbody id="tbody">
</tbody>
</table>
</body>
<script src="/static/jquery-3.3.1.js"></script>
<script>
$.ajax({
type: 'get',
url: '/backend/ajax_asset/',
success:function(args){
console.log(args);
init_thead(args['table_config']);
init_tbody(args['data_list'], args['table_config'])
}
});
function init_thead(thead_dic){
$.each(thead_dic, function(k,v){
th_str = v.title;
var th = document.createElement('th');
th.innerText = th_str;
$('#thead').append(th);
});
}
function init_tbody(data_list, thead_dic){
/**
* [
* {'id': 1, 'hostname': 'c1.com', 'sn': '432t4173t21'},
* {'id': 2, 'hostname': 'c2.com', 'sn': 'gfdgfd43432'}
* ]
*/
$.each(data_list, function(k,v){
var tr = document.createElement('tr');
$.each(thead_dic, function (k, configitem) {
/**
* {
"field": 'sn',
"title": 'sn号',
}
* @type {HTMLTableDataCellElement}
*/
var td = document.createElement('td');
td.innerText = v[configitem['field']];
console.log(td);
tr.append(td)
});
$('#tbody').append(tr);
});
}
</script>
</html>
通过此种方法加载数据,既可以减轻数据库的访问压力,又可以灵活的向前端传送数据,快速移植