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