Ajax应用
一、瀑布流的ajax应用(乐乎网站有瀑布流的案例)
1、制作原理
- 列等宽型瀑布流:花瓣网
- 画图说明
2、准备的文件
- 数据文件接口
- ajax函数(已经封装好)
3、函数的编写
布局:
<body>
<ul id="ul1">
<li>
<div>
<img src="http://www.wookmark.com/images/thumbs/625287_wookmark.jpg"/>
<p>Home | Sampoerna University</p>
</div>
</li>
<li></li>
<li></li>
<li></li>
</ul>
</body>
样式:
<style>
body {margin: 0;}
#ul1 {width: 1080px; margin: 100px auto 0;}
li { width: 247px; list-style: none; float: left; margin-right: 10px; }
li div {border: 1px solid #000; padding: 10px; margin-bottom: 10px;}
li div img { width: 225px; display: block;}
</style>
准备文件:ajax.js和数据文件接口(后台给你的文件)
function ajax(method, url, data, success) {
var xhr = null;
try {
xhr = new XMLHttpRequest();
} catch (e) {
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
if (method == 'get' && data) {
url += '?' + data;
}
xhr.open(method,url,true);
if (method == 'get') {
xhr.send();
} else {
xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
xhr.send(data);
}
xhr.onreadystatechange = function() {
if ( xhr.readyState == 4 ) {
if ( xhr.status == 200 ) {
success && success(xhr.responseText);
} else {
alert('出错了,Err:' + xhr.status);
}
}
}
}
php函数:
getPics.php
<?php
header('Content-type:text/html; charset="utf-8"');
/*
API:
getPics.php
参数
cpage : 获取数据的页数
*/
$cpage = isset($_GET['cpage']) ? $_GET['cpage'] : 1;
$url = 'http://www.wookmark.com/api/json/popular?page=' . $cpage;
$content = file_get_contents($url);
$content = iconv('gbk', 'utf-8', $content);
echo $content;
?>
函数的编写1:
<script src="ajax.js"></script>
<script>
window.onload = function() {
var oUl = document.getElementById('ul1');
var aLi = oUl.getElementsByTagName('li');
var iLen = aLi.length;
var iPage = 1;
var b = true;
//初始化数据处理
getList();
function getList() {
ajax('get','getPics.php','cpage=' + iPage,function(data) {
var data = JSON.parse(data);
if ( !data.length ) {
//后续没有数据了
return ;
}
for ( var i=0; i<data.length; i++ ) {
//获取高度最短的li
var _index = getShort();
var oDiv = document.createElement('div');
var oImg = document.createElement('img');
oImg.src = data[i].preview;
oImg.style.width = '225px';
oImg.style.height = data[i].height * ( 225 / data[i].width ) + 'px';
oDiv.appendChild( oImg );
var oP = document.createElement('p');
oP.innerHTML = data[i].title;
oDiv.appendChild( oP );
aLi[_index].appendChild( oDiv );
}
b = true;
});
}
window.onscroll = function() {
var _index = getShort();
var oLi = aLi[_index];
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
if ( getTop( oLi ) + oLi.offsetHeight < document.documentElement.clientHeight + scrollTop ) {
if ( b ) {
b = false;
iPage++;
getList();
}
}
}
function getShort() {
var index = 0;
var ih = aLi[index].offsetHeight;
for (var i=1; i<iLen; i++) {
if ( aLi[i].offsetHeight < ih ) {
index = i;
ih = aLi[i].offsetHeight;
}
}
return index;
}
function getTop(obj) {
var iTop = 0;
while(obj) {
iTop += obj.offsetTop;
obj = obj.offsetParent;
}
return iTop;
}
}
</script>
效果如下:
花瓣网效果: