web\views.pycss
import json from django.shortcuts import render,HttpResponse from django.http import JsonResponse from repository import models def server(request): return render(request,'server.html') def server_json(request): server_list = models.Server.objects.values('hostname','sn','os_platform') response = { 'status':True, 'data_list': list(server_list), } return JsonResponse(response)
server.htmlhtml
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="/static/plugins/bootstrap/css/bootstrap.css" /> </head> <body> <h1>服务器列表</h1> <script src="/static/js/jquery-3.2.1.js"></script> <script> $(function () { init(); }); /* 像后台获取数据 */ function init() { $.ajax({ url:'/server_json.html', type: 'GET', data: {}, dataType: 'JSON', success:function (response) { console.log(response.data); } }) } </script> </body> </html>
解决了什么问题?前端
具体代码以下:jquery
import json from django.shortcuts import render,HttpResponse from django.http import JsonResponse from repository import models def server(request): return render(request,'server.html') def server_json(request): table_config = [ { 'q': 'hostname', 'title': '主机名', }, { 'q': 'sn', 'title': '序列号', }, { 'q': 'os_platform', 'title': '系统', }, ] values = [] for item in table_config: values.append(item['q']) server_list = models.Server.objects.values(*values) response = { 'data_list': list(server_list), 'table_config': table_config } return JsonResponse(response)
解决了什么问题?web
一、先后端分离ajax
二、data里面再写个列表,数据库
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="/static/plugins/bootstrap/css/bootstrap.css" /> </head> <body> <div class="container"> <h1>服务器列表</h1> <table class="table table-bordered"> <thead id="tHead"> <tr> </tr> </thead> <tbody id="tBody"> </tbody> </table> </div> <script src="/static/js/jquery-3.2.1.js"></script> <script> $(function () { init(); }); /* 像后台获取数据 */ function init() { $.ajax({ url:'/server_json.html', type: 'GET', data: {}, dataType: 'JSON', success:function (response) { /* 处理表头 */ initTableHead(response.table_config); console.log(response.table_config); console.log(response.data_list); } }) } function initTableHead(table_config) { /* table_config = [ { 'q': 'hostname', 'title': '主机名', }, { 'q': 'sn', 'title': '序列号', }, { 'q': 'os_platform', 'title': '系统', }, ] */ $('#tHead tr').empty(); $.each(table_config,function (k,conf) { var th = document.createElement('th'); th.innerHTML = conf.title; $('#tHead tr').append(th); }); } </script> </body> </html>
先总体后单独django