AJAX无限滚动多次加载相同的结果

时间:2014-10-31 13:52:18

标签: jquery ajax scroll

我尝试编写一个函数,在用户scrools到页面末尾时加载搜索结果。为此,我在数据库中存储了一个搜索ID以及SQL查询字符串和当前迭代中第一个显示元素的索引(在SQL查询中的LIMIT关键字之后)。

问题是,当我慢慢滚动页面时,它可以正常工作。当我快速滚动它时,它会加载两次相同的结果,因为AJAX函数被触发两次。我该如何解决这个问题?

这是我的代码:

HTML:

<div>Result 1</div>
...
<div>Result N</div>
<div class="s-cache" data-cache="504" style="display:none" align="center"><img src="/images/ajax-loader.gif"></div>

JQuery的:

$(function() {
    $(window).scroll(function() {
        if ($(window).scrollTop() + document.body.clientHeight == $(document).height()) {
            var sCache = $('.s-cache');
            if (sCache.length) {
                //Show gif image
                sCache.show();
                var cache = sCache.data("cache");
                //Get search id
                $.ajax('selectproperty3.php', {
                    type: 'POST',
                    data: {
                        "cache": cache
                    },
                    success: function(response) {
                        //Remove div with the last iteration id
                        $('.a-clear').remove();
                        $("#dynamic").append(response);
                    },
                    error: function(request, errorType, errorMessage) {
                        $('#dynamic').html("Error: " + errorType + errorMessage);
                    }
                });
            }
        }
    });
});

MYSQL表 searchcache 包含 id 搜索 ind 字段。例如id = 504,search =&#34; SELECT * FROM properties WHERE id&gt; 0&#34;,ind = 12。

PHP:

$cache=(int)$_POST['cache'];
$num_imtems=12;
$sql = "SELECT * FROM searchcache WHERE id='$cache'";
$sql_result = mysql_query($sql) or die (mysql_error());

if (mysql_num_rows($sql_result)==0) {
    echo "Error with the cache";
    exit();
} else {
    $sql_row = mysql_fetch_row($sql_result);
    $query = stripslashes($sql_row[1]);
    $index = $sql_row[2]+$num_imtems;
}

$result = mysql_query($query) or die (mysql_error());
$total = mysql_num_rows($result);
$subquery = $query." LIMIT ".$index.",".$num_imtems;
$subresult= mysql_query($subquery) or die (mysql_error());
$nextstep = $total > ($index+$num_imtems);

...Display search results...

if ($nextstep) {
    $query = mysql_real_escape_string($query);
    $insert_query = "INSERT INTO searchcache (search,ind) VALUES ('$query','$index')";
    $insert_result = mysql_query($insert_query) or die (mysql_error());
    echo ("<div class=\"s-cache\" data-cache=\"".mysql_insert_id()."\" style=\"display:none\" align=\"center\"><img src=\"/images/ajax-loader.gif\"></div>");
}

0 个答案:

没有答案