2

我是 ajax/php 的新手,所以我想找出最好的方法。

我有一个 sql 数据库填充 1500 个项目,我正在加载到我的页面中。我想将 30 个项目加载到页面中,然后当用户到达网页底部时,我希望它再加载另外 30 个项目。

到目前为止,我的网页上显示了 30 个项目,并带有一个过滤这些项目的下拉菜单。我还有一个在用户到达页面底部时触发的函数。

任何人都可以帮助我使用 PHP 脚本来完成这项工作并加载更多项目吗?我正在使用的代码如下。

谢谢

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);
?> 
4

1 回答 1

6

这是一个相当复杂的问题。在尝试从头开始编写您自己的变体之前,我建议您看一下Infinite Scroll jQuery Plugin。如果这不能解决它,这是一个可能的解决方案:

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();

Javascript 代码向 php 脚本发送一个 AJAX GET 请求,其中包含列表中显示的最后一个条目的 id。然后,PHP 脚本会返回该 id 之后的 30 个条目。原始的 Javascript 文件中有一些 PHP 代码。我删除了它,因为我不知道它的目的是什么(你可能是从 PHP 脚本输出 JS 吗?)。此外,整个XMLHttpRequest代码可以缩短为$.get()函数。无论如何,您都在使用 jQuery,因此您无需重新发明轮子。我使用该data-id属性来传输条目 ID。这是一个 HTML5 特定的属性。如果您不想使用它,只需使用它id,但请记住 id 不能以数字开头 - 您应该在其前面加上一个字母。

在 PHP 脚本中,我使用了函数mysqli来代替。mysql_*从现在开始,您应该使用mysqlior PDO,因为它们比 (now deprecated) 更可靠和安全mysql_*。您的 PHP 安装很可能已经包含这些扩展。请注意,我没有处理数据库查询错误。您可以自己编写该代码。如果您遇到其他类型的错误,请在此处发布,我会尝试修复它们。

于 2012-08-09T09:22:16.900 回答