使用JavaScript和四个div,将照片放入四个div中
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .container { width: 1000px; margin: 0 auto; background-color: lightgray; } .item { width: 24%; margin-right: 10px; float: left; } .item img{ width: 100%; } </style> </head> <body> {#将内容放在container中#} <div> {# 将图片内容放入四个item中,形成四个item#} <div></div> <div></div> <div></div> <div></div> </div> <script src="https://www.jb51.net/static/js/jquery-2.1.4.min.js"></script> <script> $(function () { {# 网页加载时自动执行#} var obj = new ScrollImg(); obj.fetchImg(); obj.scrollEvent(); }) {# 定义对象#} function ScrollImg() { this.nid = 0; {# 取照片方法#} this.fetchImg = function () { var that = this $.ajax({ url: '/get_imgs.html', type: 'GET', {# 传输数据,已经取了多少照片,后台可以依据,继续取照片#} data: {'nid': that.nid}, dataType: 'JSON', success: function (args) { if (args.status) { var img_list = args.data; $.each(img_list, function (index, obj) { var eqv = that.nid % 4; var tag = document.createElement('img') tag.src = 'https://www.jb51.net/' + obj.img_dir; console.log(eqv) $('.container').children().eq(eqv).append(tag) that.nid += 1; }) } } }) } {# 监听滚动条,当滚到底部时,自动加载数据#} this.scrollEvent = function () { var that = this; $(window).scroll(function () { var srollTop = $(window).scrollTop(); var winHeight = $(window).height(); var docHeight = $(document).height(); if (srollTop + winHeight >= docHeight - 2) { that.fetchImg(); } }) } } </script> </body> </html>
后台内容:
基于Django的FBV,函数视图,进行数据的读取和处理ajax请求
def get_imgs(request): # 获取已经取得的照片数目 index = request.GET.get('nid') #获取QuerySet集合对象,取从index后的10调数据 imgs_list = models.Student.objects.values('id','img_dir','name')[index:index+10] imgs_list = list(imgs_list) # 传送状态和数据内容 ret = { 'status':True, 'data':imgs_list } return JsonResponse(ret)