这里只对滚动加载更多这一知识点进行整理
效果展示:
首先说一下在写demo的时候遇见的问题:
- jQuery版本引入问题
- chrome浏览器请求网络时跨域问题
我首次引入的是jQuery v1.9.0,运行时报错如下:
Uncaught Error: Syntax error, unrecognized expression:这里是用Underscore定义的一个模版内容,具体模版内容见代码。
后来改用了jQuery v1.12.4,运行正常。
搜索了一下问题,找了一下可能的原因,发现可能是jQuery v1.9.0不支持往一个div中append一个对象,而我将模版封装成了一个对象,模版作为字符串append进去的时候完全没有问题。所以引入的时候最好还是用最新版本,避免不必要的错误。
在chrome上运行时,报如下错误:
Failed to load http://127.0.0.1:3000/home/recommend?page=0: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘null’ is therefore not allowed access.
所以在服务器端send数据之前添加了一个header
res.setHeader(“Access-Control-Allow-Origin”, “*”);
问题就解决了。
核心文件引入:
- jquery.min.js
- underscore-min.js
- bootstrap.min.css
页面布局:
<ul class="box"></ul>
部分代码块如下:
定义的模版:
<script type="text/template" id="tpl">
<li >
<article>
<p>
<span>{{= author}}</span><span> · </span>
<span>{{= datetime }}</span><span> · </span>
<span>{{= category }} </span>
</p>
<h4>{{= title }}</h4>
<div class="btn-group" role="group" aria-label="...">
<button type="button" class="btn btn-default btn-xs">
<span class="glyphicon glyphicon-heart"></span>
4
</button>
<button type="button" class="btn btn-default btn-xs">
<span class=" glyphicon glyphicon-thumbs-down"></span>
1
</button>
</div>
<div class="btn-group share" role="group" aria-label="...">
<button type="button" class="btn btn-default btn-xs">
<span class="glyphicon glyphicon-share"></span>
</button>
<button type="button" class="btn btn-default btn-xs">
<span class="glyphicon glyphicon-star"></span>
</button>
</div>
</article>
</li>
</script>
封装请求数据的方法:
function getData(page){
$.ajax({
"url":"http://127.0.0.1:3000/home/recommend?page="+(nowpage-1),
"type":"get",
"success":function(data,result){
// 打印数据
console.log(data);
var datas = data.result;
// 数据迭代
iterator(0);
function iterator(i){
var zidian = compiled(datas[i]);
// $(zidian)可以将字符串转化成对象
$(".box").append($(zidian));
//$(".box").append(zidian);
iterator(i+1);
}
}
})
渲染数据:
// 得到模版内容
var tpl = $("#tpl").html();
// 模版函数
var compiled = _.template(tpl);
var nowpage =1;
getData(nowpage);
滚动监听:
$(window).scroll(function() {
var scrollTop = $(this).scrollTop(),
// 文档高度
scrollHeight = $(document).height(),
windowHeight = $(this).height();
var positionValue = (scrollTop + windowHeight) - scrollHeight;
if (positionValue >= 0) {
// load more
// alert("现在要取请求更多数据");
getData(++nowpage);
}else{
}
});