使用 AJAX 将结果添加到页面底部


Using AJAX to add results to the bottom of a page

我有一些代码可以遍历一些数据库结果并显示它们,因此...注意:文章项目.php只是用一些格式回显结果。

 <ul class="post-column">
                            <?php 
                            foreach ($data as $lineitem):
                            $type = $lineitem['type'];
                            if($type == "article"){
                               require('php/articleitem.php');
                            }
                            endforeach; 
                            ?>
                        </ul>

当我到达页面底部时,我想执行 AJAX DB 调用以获得进一步的结果......

if ($(window).scrollTop() >= $(document).height() - $(window).height() - 700) {
        startpoint = startpoint + 10;
        processing = true;
        $.ajax({
            url: "AJAX/moritems.php",
            type: "post",
            async: false,
            //this is where we define the data that we will send
            data: {
                startpoint: startpoint,
            },
            success: function (data) {
            },
        });
        processing = false;
    }

然后,我想使用数据库结果在屏幕上已经显示的数据下方显示更多数据,但是由于到目前为止我已经在 PHP 中显示了结果,我将如何做到这一点?我是否必须使用 AJAX 加载带有结果的新 php 页面,然后使用 javascript 将其添加到结果底部的现有页面?

答案是肯定的。例:

function load() {
    var xmlhttp;
    xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
           if(xmlhttp.status == 200){
               document.getElementById("myDiv").innerHTML += xmlhttp.responseText;
           }
           else if(xmlhttp.status == 400) {
              alert('There was an error 400')
           }
           else {
               alert('something else other than 200 was returned')
           }
        }
    }
    xmlhttp.open("GET", yoururl, true);
    xmlhttp.send();
}

您需要定义yoururl并将函数链接到分页按钮的click事件,或者在scroll时运行它。