class MyDateTimeEncode(json.JSONEncoder):
def default(self, o):
if isinstance(o, datetime):
return o.strftime('%Y-%m-%d %H:%M:%S')
elif isinstance(o, date):
return o.strftime('%Y-%m-%d')
else:
return json.JSONEncoder.default(self, o) def seriallizer_view(request):
books_obj = models.Book.objects.all()
# 传queryset对象
# json_books_obj = serializers.serialize('json', books_obj)
time1 = datetime.now()
json_time1 = json.dumps(time1, cls=MyDateTimeEncode)
if request.method == "POST":
return HttpResponse(json_time1)
# return JsonResponse({"key": 'OK'}) # 默认只能传值字典,其余字符串等需要设置参数safe=False
return render(request, 'serial.html')
前端ajax代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.bootcss.com/vue/2.5.17-beta.0/vue.js"></script>
<script src="https://cdn.bootcss.com/vue-router/3.0.1/vue-router.js"></script>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script src="https://cdn.bootcss.com/jquery-cookie/1.4.1/jquery.cookie.js"></script>
</head>
<body>
<button id="btn">点我获取数据</button> <script>
$("#btn").click(function () {
{#$.ajax({#}
{# url:"",#}
{# type:'post',#}
{# contentType:'json',#}
{# headers:{"X-CSRFToken":$.cookie("csrftoken")},#}
{# data:{},#}
{# success:function (res) {#}
{# data = JSON.parse(res);#}
{# console.log(data[0]);#}
{# console.log(typeof res);#}
{# for(var i=0;i<data.length;i++)#}
{# $("body").append(`<li>${data[i].fields.title}</li>`)#}
{# }#}
{#)#}
$.ajax({
url:"",
type:'post',
contentType:'json',
headers:{"X-CSRFToken":$.cookie("csrftoken")},
data:{},
success:function (res) {
console.log(res);
console.log(typeof JSON.parse(res))
}
})
}) </script>
</body>
</html>
ajax代码