在Django框架中使用
前端以及Ajax
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.w {
width: 1000px;
margin: 0 auto;
}
.item {
width: 25%;
float: left;
}
.item img {
width: 100%;
}
</style>
</head>
<body>
<div>姑娘们</div>
<div class="w" id="container">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
<script src="/static/jquery-1.12.4.js"></script>
<script>
//封装在一个对象里使用 因为有全局变量 避免冲突
$(function () {
var obj = new ScrollImg();
obj.fetchImg();
obj.scrollEvent();
});
function ScrollImg() {
this.NID = 0;
this.LASTPOSITION = 3;
this.fetchImg = function () {
var that = this;
$.ajax({
url: '/get_imgs.html',
type: 'GET',
data: {nid: that.NID},
dataType: 'JSON',
success: function (arg) {
var img_list = arg.data;
$.each(img_list, function (index, v) {
var eqv = (index + that.LASTPOSITION + 1) % 4;
console.log(eqv);
var tag = document.createElement('img');
tag.src = '/' + v.src;
$('#container').children().eq(eqv).append(tag);
//单循环到最后一个图片时,将图片id赋值给NID
if (index + 1 == img_list.length) {
that.LASTPOSITION = eqv;
//that.NID = v.id;
//数据库中图片很多可以使用,这里用来试验
}
})
}
})
};
//当滑轮到底最底部时,执行
this.scrollEvent = function () {
var that = this;
$(window).scroll(function () {
//什么时候达到最底部
var scrollTop = $(window).scrollTop(); //滚动条可滑动的高度
var winHeight = $(window).height(); //窗口高度
var docHeight = $(document).height(); //文档高度
if (scrollTop + winHeight == docHeight) {
that.fetchImg();
}
})
}
}
</script>
</body>
</html>
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^imgs.html$', views.imgs),
url(r'^get_imgs.html$', views.get_imgs),
]
from django.shortcuts import render, HttpResponse
from django.http import JsonResponse
from app01 import models
import json
def imgs(request):
return render(request, 'img.html')
def get_imgs(request):
nid = request.GET.get('nid')
img_list = models.Img.objects.filter(id__gt=nid).values('id', 'src', 'title')
img_list = list(img_list)
ret = {
'status': True,
'data': img_list
}
return JsonResponse(ret)