Click to load more

Basic principle: When the page is loaded, it requests data from the background, and PHP displays the latest records on the list page by querying the database. There is a "more" link at the bottom of the list page. By triggering the link, send the data to the server. Ajax request, the background PHP program gets the request parameters and responds accordingly, obtains the corresponding records in the database and returns them to the front page in the form of JSON, and the front page jQuery parses the JSON data and appends the data to the list page. In fact, it is the effect of Ajax paging.

 

1. Introduce jquery library and jquery.more.js plug-in, jquery.more.js has encapsulated many functions and provides the function of parameter configuration.

 

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.more.js"></script>

 2 html structure

 

 

	<ul id="more" style="display: block;">						
             <li class="show-box">
		 <div class="box">
		      <div class="left">
	                   <a href="url"><img src="thumbUrl"></a>					      </div>
		      <div class="right">
		           <a href="#" class="title"></a>
				<p class="digest"></p>
			        <span class="time">
				<i></i>
				<span class="updateTime"></span>
			        </span>
		      </div>
		</div>
	    </li>
	    <li class="loadMore"><a href="javascript:;">加载更多>></a></li>
        </ul>

The title digest updatatime in the page corresponds to the attribute name in the data. loadMore is associated with the jquery.more.js plugin. You can also choose another class name, but you must write the corresponding class when configuring.

 

js

$(function(){
	$('#more').more({'address': 'http://192.168.3.233:8000/agriculture/ajax/info'})
});

 php

require_once('connect.php');
 
$last = $_POST['last'];
$amount = $_POST['amount'];
 
$user = array('demo1','demo2','demo3','demo3','demo4');
$query=mysql_query("select * from say order by id desc limit $last,$amount");
while ($row=mysql_fetch_array($query)) {
    $sayList[] = array(
        'content'=>$row['content'],
        'author'=>$user[$row['userid']],
        'date'=>date('m-d H:i',$row['addtime'])
      );
}
echo json_encode($sayList);

Receive the two parameters submitted by the front page, $_POST['last'] is the number of records to start, $_POST['amount'] is the number of records displayed at a time, and you can see from the SQL statement that it is actually the statement used in paging .

Then the result of the query is output in JSON format, and the task of PHP is completed.

Finally, let's take a look at the parameter configuration of jquery.more.js.

'amount' : '10', //The number of records displayed each time
'address' : 'comments.php', //The address of the request background
'format' : 'json', //data transmission format
'template' : '.show-box', //html records the class attribute of DIV
'trigger' : '. loadMore ', // class attribute that triggers loading more records
'scroll' : 'false', //whether scroll trigger loading is supported
'offset' : '100', // offset when scroll triggers loading

 

 jquery.more.js file

(function( $ ){          
    var target = null;
    var template = null;
    var lock = false;
    var variables = {
        'last'      :    0        
    }
    var settings =
        'amount'      :   '10',          
        'address'     :   'comments.php',
        'format'      :   'json',
        'template'    :   '.show-box',
        'trigger'     :   '.loadMore',
        'scroll'      :   'false',
        'offset'      :   '100',
        'spinner_code':   ''
    }
    
    var methods = {
        init  :   function(options){
            return this.each(function(){
              
                if(options){
                    $.extend(settings, options);
                }
                template = $(this).children(settings.template).wrap('<div/>').parent();
                template.css('display','none')
                $(this).append('<div class="more_loader_spinner">'+settings.spinner_code+'</div>')
                $(this).children(settings.template).remove()   
                target = $(this);
                if(settings.scroll == 'false'){                    
                    $(this).find(settings.trigger).bind('click.more',methods.get_data);
                    $(this).more('get_data');
                }                
                else{
                    if($(this).height() <= $(this).attr('scrollHeight')){
                        target.more('get_data',settings.amount*2);
                    }
                    $(this).bind('scroll.more',methods.check_scroll);
                }
            })
        },
        check_scroll : function(){
            if((target.scrollTop()+target.height()+parseInt(settings.offset)) >= target.attr('scrollHeight') && lock == false){
                target.more('get_data');
            }
        },
        debug :   function(){
            var debug_string = '';
            $.each(variables, function(k,v){
                debug_string += k+' : '+v+'\n';
            })
            alert(debug_string);
        },     
        remove        : function(){            
            target.children(settings.trigger).unbind('.more');
            target.unbind('.more')
            target.children(settings.trigger).remove();
        },
        add_elements  : function(data){
            //alert('adding elements')
            
            var root = target       
         //   alert(root.attr('id'))
            var counter = 0;
            if(data){
                $(data).each(function(){
                    counter++
                    var t = template                    
                    $.each(this, function(key, value){                          
                        if(key == 'url'){
                            //console.log(t.find('.'+key))
                            t.find('.'+key).attr("href",value)
                        }else if (key == 'thumbUrl'){
                            var newvalue = '/'+value;
                            t.find('.'+key).attr("src",newvalue)
                        } else {
                            //console.log(key)
                            t.find('.'+key).html(value)
                        }
                    })         
                    //t.attr('id', 'more_element_'+ (variables.last++))
                    if(settings.scroll == 'true'){
                    //    root.append(t.html())
                    root.children('.more_loader_spinner').before(t.html())  
                    }else{
                    //    alert('...')
                          
                          root.children(settings.trigger).before(t.html())  

                    }

                    root.children(settings.template+':last').attr('id', 'more_element_'+ ((variables.last++)+1))  
                 
                })
                
                
            }            
            else  methods.remove()
            target.children('.more_loader_spinner').css('display','none');
            if(counter < settings.amount) methods.remove()            

        },
        get_data      : function(){   
           // alert('getting data')
            with var;
            lock = true;
            target.children(".more_loader_spinner").css('display','block');
            $(settings.trigger).css('display','none');
            if(typeof(arguments[0]) == 'number') ile=arguments[0];
            else {
                ile = settings.amount;              
            }
            
            $.post(settings.address, {
                last : variables.last,
                amount : ile                
            }, function(data){            
                $(settings.trigger).css('display','block')
                methods.add_elements(data)
                lock = false;
            }, settings.format)
            
        }
    };
    $.fn.more = function(method){
        if(methods[method])
            return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
        else if(typeof method == 'object' || !method)
            return methods.init.apply(this, arguments);
        else $.error('Method ' + method +' does not exist!');

    }    
})(jQuery)

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326605812&siteId=291194637