需求
最近需要用到表格分页管理的相关内容, 所以用到了 datatable 框架
html 部分
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="shortcut icon" type="image/ico" href="http://www.datatables.net/favicon.ico">
<meta name="viewport" content="initial-scale=1.0, maximum-scale=2.0">
<title>DataTables example - Ajax data source (objects)</title>
<link rel="stylesheet" type="text/css" href="/static/dtable/media/css/jquery.dataTables.css">
<style type="text/css" class="init"></style>
<script type="text/javascript" language="javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script type="text/javascript" language="javascript" src="/static/dtable/media/js/jquery.dataTables.js"></script>
<script>
</script>
<script type="text/javascript" language="javascript" class="init">
$(document).ready(function() {
$.ajax({
type:"GET",
url:"/dtb/dtable_json/", //测试用,test_list
dataType:"json",
//data: {dat:dict},
success:function(res){
var heads = res.heads
var columns = new Array()
var head_tr = document.getElementById("origin_tr")
var tr_inner_html = ""
for(var i=0; i<heads.length; i++){
columns.push({"data": heads[i]})
tr_inner_html += "<th>" + heads[i] + "</th>" + "\n"
}
head_tr.innerHTML = tr_inner_html
// 注意这里可以直接用 ajax 但是不利于管理。
$('#example').DataTable({
"data": res.data,
"columns": columns,
});
}
});
} );
</script>
</head>
<body class="dt-example">
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr id="origin_tr">
</tr>
</thead>
</table>
</body>
</html>
views 部分
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.template import RequestContext,loader
import json
import pymysql
def index(request):
template = loader.get_template('dtable/index.html')
data = {}
return HttpResponse(template.render(data))
def get_loc_df(sql):
conn = pymysql.connect(
host='localhost',
user='root',
password='112233..',
db='12306',
charset='gbk',
)
corsor = conn.cursor()
corsor.execute(sql)
res = corsor.fetchall()
corsor.close()
conn.close()
return res
def test_json(request):
resource_sql = get_loc_df("select email,idnum,username,tel,password from user limit 450")
res = []
for x in resource_sql:
temp = {}
temp.setdefault("email", x[0])
temp.setdefault("idnum", x[1])
temp.setdefault("username", x[2])
temp.setdefault("tel", x[3])
temp.setdefault("password", x[4])
res.append(temp)
data = {"data": res, "heads": ["email", "idnum", "username", "tel", "password"]}
return JsonResponse(data)