js下拉加载插件

2017/05/30 22:36
阅读数 48
// 使用
// new ManDownLoad("#ul","json/load.json",function(data,obj){
//   var str = "";
//   data.data.forEach(function(item,index){
//      str += "<li>" + item.title + "</li>";
//   });
//   return str;
// },{
//  type:"POST",
//  data:{
//    "hello":"world",
//    "fa":"bbb"
//  }
// });
;function ManDownLoad(element,url,callback,obj){
  this.element = element;
  if((typeof element)==="string"){
    this.element = document.querySelector(element);
  }
  this.url = url;
  this.callback = callback;
  var options = {
    type:"GET",
    distance:0,
    dataType:"json",
    data:{}
  };
  this.config = this.extend(options,obj);
  this.init();
};
ManDownLoad.prototype = {
  init:function(){
    var _this = this;
    this.isBottom();
    window.addEventListener("scroll",this.isBottom);
  },
  // 判断是否到达底部
  isBottom:function(){
    var _this = this;
    var scrollH = null,
        clientHeight = null,
        scrollTop = null,
        h = 0;

    scrollH = document.body.scrollHeight||document.documentElement.scrollHeight;
    clientHeight = window.innerHeight;
    scrollTop = document.body.scrollTop||document.documentElement.scrollTop;
    h = clientHeight + scrollTop;
    if(h>=scrollH-_this.config.distance){
      _this.ajax();
    }
  },
  // 发送AJAX请求
  ajax:function(){
    var _this = this;
    var xhr = new XMLHttpRequest();
    var data = null;
    
    xhr.open(this.config.type,this.url,true);
    xhr.onreadystatechange = function(){
      if(xhr.readyState==4&&xhr.status==200){
        if(_this.config.dataType==="json"){
          data = _this.callback(JSON.parse(xhr.responseText),_this);
        }else{
          data = _this.callback(xhr.responseText,_this);
        }
        if(data===false){
            window.removeEventListener("scroll",_this.isBottom);
        }
        _this.addHTML(data,function(){
          _this.isBottom();
        });
      }
    }
    xhr.send(_this.toFormStr(_this.config.data));
  },
  addHTML:function(data,callback){
    if(!data)return;
    if((typeof data)==="string"){
        this.element.innerHTML += data;
    }else{
        this.element.appendChild(data);
    }
    callback&&callback();
  },
  toFormStr:function(obj){
    var str = "";
    for(var k in obj){
        str += k + "=" + obj[k] + "&";
    }
    return str.slice(0,-1);
  },
  extend:function(obj,obj2){
    if(!obj)return obj2;
    for(var k in obj2){
        obj[k] = obj2[k];
    }
    return obj;
  }
};

 

展开阅读全文
js
加载中

作者的其它热门文章

打赏
0
0 收藏
分享
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部