python+django+mysql 从零搭建资讯类网站09
系列文章将记录本人从零开始搭建资讯类的网站,所有源码都开放哦!欢迎互相讨论学习!
源码下载地址:https://github.com/wuqiwenpk/babyteach
本系列文章导航:https://github.com/wuqiwenpk/babyteach/blob/master/README.md
本篇目的
使用ajax异步加载详情页、搜索页中热门资讯列表数据。
1、修改models.py添加点击量字段clicks
执行代码提交到数据库:
python manage.py makemigrations
python manage.py migrate
2、修改views.py视图文件,添加获取热门数据方法
获取列表数据,根据点击量排行来获取前10条数据:
#获取列表页和详情页热点资讯排名 def gethottagslist(request): hotlist = Detail.objects.order_by('clicks')[0:10].values('id', 'title') print(hotlist) return JsonResponse({'hotlist': list(hotlist)})
3、修改urls.py文件添加路由
path('search/gethottagslist', views.gethottagslist),#获取热点资讯
4、修改search.html和detail.html文件添加ajax方法
<div class="bg-gray p-2"> <ul class="bg-white pt-0 pb-0 pl-3 pr-3 border" style="border-top: 2px solid #d6181d !important;"> <div id="hotlist" class="bg-white text-red font-weight-light- font-s18 pt-3 pb-2">资讯热点排名</div> </ul> </div>
<script> $(function(){ //加载热点资讯 $.ajax({ type:'post', url:'/search/gethottagslist', success:function(datas){ for(i=0;i<datas.hotlist.length;i++){ var num =i+1; $("#hotlist").append("<li class='d-flex justify-content-between align-items-center align-middle border-top pt-3 pb-3'><a href='/detail/"+datas.hotlist[i].id+"' class='font-weight-light font-s14' target='_blank' style='color:;font-weight:;'><span class='badge badge-red text-white font-weight-light mr-2'>"+num+"</span>"+datas.hotlist[i].title+"</a><span class='font-weight-light font-s14 text-gray'></span></li>"); } } }); }); </script>
5、重新运行网站测试
本文总结:
使用ajax异步加载详情页、搜索页中热门资讯列表数据。
完整源码地址:https://github.com/wuqiwenpk/babyteach