加载多个项目数据库〜无限滚动 [英] Loading more items from database ~ Infinite Scroll

查看:97
本文介绍了加载多个项目数据库〜无限滚动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的Ajax / PHP所以我试图找出这样做的最好方法。

我有1500项,我加载到我的网页SQL数据库填充。我想加载30个项目进入页面,然后当用户到达我希望它再加载另一个30项网页的底部。

到目前为止,我有30个项目显示在我的网页,有一个下拉菜单,过滤项目。我还有一个功能,当用户获取到页面底部闪光。

任何人都可以帮助我的PHP脚本,使这项工作,并加载更多的项目?在code我现在用的就是以下。

感谢

HTML

 <节ID =过滤器>
    <选择名称=项的onchange =filterEntries()>
        <期权价值=*>显示所有的< /选项>
        <期权价值=item323。> 323< /选项>
        <期权价值=item266。> 266< /选项>
        <期权价值=item277。> 277< /选项>
        <期权价值=item289。> 289< /选项>
    < /选择>
< /节> &所述;! -  #filters  - >

< D​​IV ID =项级=clearfix>
    < D​​IV CLASS =ajaxloader>< IMG SRC =< PHP代码bloginfo('template_url');?> /ajax_load.gifALT =加载.../>< / DIV&GT ;&其中;! -  ajaxloader  - >
< / DIV><! - 项 - >
< D​​IV CLASS =ajaxloader>< IMG SRC =< PHP代码bloginfo('template_url');?> /ajax_load.gifALT =加载.../>< / DIV&GT ;&其中;! -  ajaxloader  - >
 

jQuery的

  $(文件)。就绪(函数(){
    loadData();
    //隐藏装载机的无限滚动
    $('div.ajaxloader')隐藏()。

});

功能loadData(){
//显示装载机的主要内容
    $('#项.ajaxloader)显示()。
//从数据库中的数据拉
如果(window.XMLHtt prequest){// $ C $下IE7 +,火狐,Chrome,歌剧,Safari浏览器
        使用严格;
        XMLHTTP =新XMLHtt prequest();
    }
    其他{// code对IE6,IE5
        XMLHTTP =新的ActiveXObject(Microsoft.XMLHTTP);
    }
    xmlhttp.onreadystatechange =功能(){
        如果(xmlhttp.readyState === 4和&安培; xmlhttp.status === 200){
        的document.getElementById(项目)的innerHTML = xmlhttp.responseText。
        一旦数据加载//消防过滤功能
            filterEntries();
            //隐藏加载器加载后主要内容
            $('#项.ajaxloader')隐藏();
    }
    }
    xmlhttp.open(POST,< PHP代码bloginfo('template_url');?> /getentries.php $多少?,真正的);
    xmlhttp.send();
};


//同位素过滤器
功能filterEntries(){
    变量$箱= $('#项目);
       $选择= $('#过滤器选择');

    $ container.isotope({
        itemSelector:.item
    });

    $ select.change(函数(){
    VAR过滤器= $(本).VAL();

    $ container.isotope({
            过滤:过滤器
    });
});
};

$(窗口).scroll(函数(){
    如果($(窗口).scrollTop()> = $(文件).height() -  $(窗口).height() -  10){
    $('div.ajaxloader')显示(慢);

        //警报(功能加载多个条目);

    }
});
 

PHP

 < PHP
    //连接到数据库
    $ CON =的mysql_connect(localhost的根,根);
    如果(!$ CON){
        死亡(无法连接:mysql_error());
    }
    mysql_select_db(奖励,$ CON);


    $ SQL =SELECT * FROM条目,其中状态='注册'ORDER BY`entry_id` LIMIT 0,30;

    $结果= mysql_query($ SQL);


    而($行= mysql_fetch_array($结果)){
        //获取奖励的猫IDS
        $ awardcat = $行['awards_subcategory_id'];

        打印< D​​IV CLASS =项项$ awardcat clearfix'>中; //加奖的猫ID为每个div
        打印'< IMG类=形象SRC =HTTP://本地主机:8888 / awardsite /可湿性粉剂内容/主题/奖励/ placeholder.jpg/>';
        打印< P>一室。 $行['工作室'。 &所述; / P>中;
        打印和LT,P级='客户'>客户:。 $行['客户'。 &所述; / P>中;
        打印和LT,P级='说明'>简介:。 $行[描述。 &所述; / P>中;
        打印和LT,P级='solutionprocess'>解决方法:。 $行['solution_process']。 &所述; / P>中;
        打印和LT; / DIV>中;

    }





    则mysql_close($ CON);
?>
 

解决方案

这是一个相当复杂的问题。在试图code自己的变化从头开始,我建议你看一看的无限滚动jQuery插件。如果不解决这个问题,这里有一个可能的解决方案:

Javascript的

  $(文件)。就绪(函数(){
    loadData(0);
    //隐藏装载机的无限滚动
    $('div.ajaxloader')隐藏()。

});

功能loadData(last_id){
    变量$项目= $('#项目),
        $装载机= $('ajaxloader。',$项).show();
    $获得('/getentries.php',{last_id:last_id},功能(数据){
        $ entries.append(数据).append($ loader.hide());
        filterEntries();
    });
};


//同位素过滤 - 没有改变这个code所以我不包括它

$(窗口).scroll(函数(){
    如果($(窗口).scrollTop()> = $(文件).height() -  $(窗口).height() -  10){
        $('div.ajaxloader')显示(慢);
        loadData($('#entries项目:去年')的.data('身份证'))
    }
});
 

PHP

 < PHP
//连接到数据库
$ CON =新的mysqli(本地主机','根','根','奖励');
如果($ CON-> connect_errno){
    死亡(无法连接:'$ CON-> connect_error。);
}

$ last_id =使用isset($ _ GET ['last_id'])? (INT)$ _ GET ['last_id']:0;
$语句= $ CON-> prepare(SELECT * FROM条目,其中状态=注册和entry_id>()ORDER BY entry_id LIMIT 0,30?);
$ stmt-> bind_param('我',$ last_id);
$ stmt->执行();

$结果= $ stmt-> get_result();
而($行= $ result-> FETCH_ASSOC()){
    //获取奖励的猫IDS
    $ awardcat = $行['awards_subcategory_id'];

    打印< D​​IV CLASS =项项$ awardcat clearfix'数据-ID ='。 $行['entry_id']。 '>中; //加奖的猫ID为每个div
    打印'< IMG类=形象SRC =HTTP://本地主机:8888 / awardsite /可湿性粉剂内容/主题/奖励/ placeholder.jpg/>';
    打印< P>一室。 $行['工作室'。 &所述; / P>中;
    打印和LT,P级='客户'>客户:。 $行['客户'。 &所述; / P>中;
    打印和LT,P级='说明'>简介:。 $行[描述。 &所述; / P>中;
    打印和LT,P级='solutionprocess'>解决方法:。 $行['solution_process']。 &所述; / P>中;
    打印和LT; / DIV>中;

}
$ CON->关闭();
 

JavaScript的code发送一个AJAX GET请求到PHP脚本列表中显示的最后一个条目的ID。 PHP脚本然后返回来了,是ID后30项。原来的JavaScript文件有一点PHP code在里面。我删除了,因为我不知道它的目的是(是否从PHP脚本输出的JS可能?)。此外,整个 XMLHtt prequest code可以缩短到 $。获得()功能。您正在使用jQuery无论如何,所以你并不需要推倒重来。我使用了数据ID 属性来传递条目号。这是一个HTML5的特定属性。如果你不想使用它,只需使用 ID 代替,但要记住,ID不能以数字开头 - 你应该preFIX用一个字母<。 / P>

在PHP脚本,我用的mysqli 而不是 mysql的_ * 功能。您应该使用的mysqli PDO 从现在开始,因为它们更可靠,比(现德$ P安全$ pcated) mysql的_ * 。你的PHP安装最有可能包含这些扩展了。请注意,我没有处理数据库查询错误。您可以编写$ C C自己$。如果看到其它类型的错误,张贴在这里,我会试着解决这些问题。

I am new to ajax/php so am trying to figure out the best way of doing this.

I have got a sql database fill of 1500 items that I am loading into my page. I want to load 30 items into the page then when the user gets to the bottom of the web page I want it to then load another 30 items.

So far I have the 30 items displaying on my webpage, with a drop down menu that filters the items. I also have a function that fires when the user gets to the bottom of the page.

Can anyone help me with the PHP script to make this work and load more items? The code I am using is below.

Thanks

HTML

<section id="filters">
    <select name="entries"  onchange="filterEntries()">
        <option value="*">show all</option>
        <option value=".item323">323</option>
        <option value=".item266">266</option>
        <option value=".item277">277</option>
        <option value=".item289">289</option>
    </select>
</section> <!-- #filters -->

<div id="entries" class="clearfix">
    <div class="ajaxloader"><img src="<?php bloginfo('template_url'); ?>/ajax_load.gif" alt="loading..." /></div><!--ajaxloader-->
</div><!--entries-->
<div class="ajaxloader"><img src="<?php bloginfo('template_url'); ?>/ajax_load.gif" alt="loading..." /></div><!--ajaxloader-->

Jquery

$(document).ready(function () {
    loadData();
    //Hide Loader for Infinite Scroll
    $('div.ajaxloader').hide();

});

function loadData () {
//Show Loader for main content
    $('#entries .ajaxloader').show();
//Pull in data from database
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        "use strict";
        xmlhttp=new XMLHttpRequest(); 
    }
    else {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState===4 && xmlhttp.status===200) {    
        document.getElementById("entries").innerHTML=xmlhttp.responseText;
        //Fire filter function once data loaded
            filterEntries();
            //Hide Loader for main content once loaded
            $('#entries .ajaxloader').hide();
    }
    }
    xmlhttp.open("POST","<?php bloginfo('template_url'); ?>/getentries.php?$number",true);
    xmlhttp.send();
};


//Isotope filter
function filterEntries () {
    var $container = $('#entries');
       $select = $('#filters select');

    $container.isotope({
        itemSelector : '.item'
    });

    $select.change(function() {
    var filters = $(this).val();

    $container.isotope({
            filter: filters
    });
});
};

$(window).scroll(function () {
    if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
    $('div.ajaxloader').show('slow');

        //alert("Function to load more entries");

    }
});

PHP

<?php
    //Connect to Database
    $con = mysql_connect("localhost", "root", "root");
    if (!$con) {
        die('Could not connect: ' . mysql_error());
    }
    mysql_select_db("awards", $con);


    $sql="SELECT * FROM entry WHERE  status = 'registered' ORDER BY `entry_id` LIMIT 0, 30";

    $result = mysql_query($sql);


    while($row = mysql_fetch_array($result)) {
        //Get award cat ids
        $awardcat =  $row['awards_subcategory_id']  ;

        print "<div class='item item$awardcat clearfix'>";//add award cat id to each div
        print '<img class="image" src="http://localhost:8888/awardsite/wp-content/themes/award/placeholder.jpg" />';
        print "<p > Studio: " . $row['studio'] . "</p>";
        print "<p class='client'> Client: " . $row['client'] . "</p>";
        print "<p class='description'> Description: " . $row['description'] . "</p>";
        print "<p class='solutionprocess'> Solution Process: " . $row['solution_process'] . "</p>";
        print "</div>";

    }





    mysql_close($con);
?> 

解决方案

This is quite a complex question. Before trying to code your own variation from scratch, I suggest you take a look at the Infinite Scroll jQuery Plugin. If that doesn't fix it, here's a possible solution:

Javascript

$(document).ready(function () {
    loadData( 0 );
    //Hide Loader for Infinite Scroll
    $('div.ajaxloader').hide();

});

function loadData ( last_id ) {
    var $entries = $('#entries'),
        $loader = $('.ajaxloader', $entries).show();
    $.get( '/getentries.php', { last_id : last_id }, function( data ) {
        $entries.append( data ).append( $loader.hide() );
        filterEntries();
    });
};


//Isotope filter - no changes to this code so I didn't include it

$(window).scroll(function () {
    if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
        $('div.ajaxloader').show('slow');
        loadData( $( '#entries item:last' ).data('id') )
    }
});

PHP

<?php
//Connect to Database
$con = new mysqli( 'localhost', 'root', 'root', 'awards' );
if( $con->connect_errno ) {
    die( 'Could not connect:' . $con->connect_error );
}

$last_id = isset( $_GET['last_id'] ) ? (int)$_GET['last_id'] : 0; 
$stmt = $con->prepare( 'SELECT * FROM entry WHERE status = "registered" AND entry_id > (?) ORDER BY entry_id LIMIT 0, 30' );
$stmt->bind_param( 'i', $last_id );
$stmt->execute();

$result = $stmt->get_result();    
while( $row = $result->fetch_assoc() ) {
    //Get award cat ids
    $awardcat = $row['awards_subcategory_id'];

    print "<div class='item item$awardcat clearfix' data-id='" . $row['entry_id'] . "'>";//add award cat id to each div
    print '<img class="image" src="http://localhost:8888/awardsite/wp-content/themes/award/placeholder.jpg" />';
    print "<p > Studio: " . $row['studio'] . "</p>";
    print "<p class='client'> Client: " . $row['client'] . "</p>";
    print "<p class='description'> Description: " . $row['description'] . "</p>";
    print "<p class='solutionprocess'> Solution Process: " . $row['solution_process'] . "</p>";
    print "</div>";

}
$con->close();

The Javascript code sends an AJAX GET request to the php script with the id of the last entry displayed in the list. The PHP script then returns 30 entries that come after that id. The original Javascript file had a bit of PHP code in it. I removed that, as I don't know what its purpose is (are you outputting the JS from a PHP script maybe?). Also, the whole XMLHttpRequest code can be shortened to the $.get() function. You're using jQuery anyway, so you don't need to reinvent the wheel. I used the data-id attribute to transmit the entry ids. That is a HTML5 specific attribute. If you don't want to use it, just use id instead, but remember that ids cannot start with a number - you should prefix it with a letter.

In the PHP script, I used mysqli instead of the mysql_* functions. You should use mysqli or PDO from now on, as they are more reliable and secure than the (now deprecated) mysql_*. Your PHP installation most likely includes these extensions already. Note that I didn't handle database querying errors. You can write that code yourself. If you get other kinds of errors, post them here and I will try to fix them.

这篇关于加载多个项目数据库〜无限滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆