django--序列化
生成一个空白页面,
def xuliehua(request):
return render(request,'xuliehua.html')
然后向后台发送Ajax请求
<script> $(function () { initData(); }); function initData() { $.ajax({ url :'/get_data/', type:'GET', success:function (arg) { console.log(arg); } } }) } </script>
接收Ajax请求的视图函数获取数据库数据
def get_data(request): user_list = models.UserInfo.objects.all() result = 序列化(user_list) HttpResponse(result)
问题:json模块只能序列化python基本数据类型,不能序列化QuerySet
from django.shortcuts import render from django.shortcuts import HttpResponse from app01 import models import json def xuliehua(request): return render(request,'xuliehua.html') """ def get_data(request): user_list = models.UserInfo.objects.all() return render(request,'get_data.html',{'user_list':user_list}) """ def get_data(request): from django.core import serializers ret = {'status':True,'data':None} try: ''' #1、QuerySet内部是对象,用django内置序列化方法进行序列化 user_list = models.UserInfo.objects.all() #QuerySet【obj,obj,obj】 ret['data'] = serializers.serialize("json",user_list) // var v = JSON.parse(arg.data); // console.log(v);''' '''#2、QuerySet内部字典,直接把QuerySet转化成列表交给json user_list = models.UserInfo.objects.all().values('id','username') ret['data'] = list(user_list) console.log(arg.data);''' '''#3、QuerySet内部是元组,直接把QuerySet转化成列表交给json user_list = models.UserInfo.objects.all().values_list('id', 'username') ret['data'] = list(user_list) console.log(arg.data);''' pass except Exception as e: ret['status'] = False result = json.dumps(ret) return HttpResponse(result)
xuliehua.html
<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) { //$('#tb').append(arg); if(arg.status){ console.log(arg.data); //var v = JSON.parse(arg.data); //如果后台传的QuerySet内部是对象, //因为在后台做了两次序列化,前端需两次反序列化 //console.log(v); } } }) } </script>