1.views.py
from django.shortcuts import render,HttpResponse
from app01 import models
# Create your views here.
def xuliehua(req):
user_list=models.UserInfo.objects.all()
return render(req,'xuliehua.html')
#第一種方式
"""
def get_data(req):
user_list = models.UserInfo.objects.all()
return render(req,'get_data.html',{'user_list':user_list})
#return HttpResponse('ok')
"""
import json
#序列化QuerySet
from django.core import serializers
def get_data(req):
ret= {'status':True,'data':None}
try:
#第一種方式
#user_list=models.UserInfo.objects.all()
#QuerySet[obj,obj,obj]
#ret['data']=serializers.serialize('json',user_list)
#第二種方式
# user_list = models.UserInfo.objects.all().values('id','username')
# ret['data']=list(user_list)
#第三種方式
user_list = models.UserInfo.objects.all().values_list('id', 'username')
ret['data'] = list(user_list)
except Exception as e:
ret['status']=False
result=json.dumps(ret)
return HttpResponse(result)
複製程式碼
2.xuliehua.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>xuliehua</title>
</head>
<body>
<h1>使用者列表</h1>
<table id="tb">
</table>
<script src="/static/jquery-3.1.1.js"></script>
<script>
$(function () {
initData();
})
function initData() {
$.ajax({
url:'/get_data/',
type:'GET',
dataType:'JSON',
success:function (arg) {
//console.log(arg)
{#$('#tb').append(arg)#}
if(arg.status){
//字串
console.log(arg.data)
//轉化為對向形式
//var v =JSON.parse(arg.data)
}
}
})
}
</script>
</body>
</html>
複製程式碼