AJAX和SQL重复结果

时间:2017-06-13 10:17:45

标签: javascript php jquery mysql ajax

我有问题,我有ajax请求和php脚本,当我点击按钮时,结果重复。

HTML和JS:

$("#more-news").click(function(e) {
    e.preventDefault();
    $.ajax({    //create an ajax request to load_page.php
        type: "GET",
        url: "/getnews.php",
        dataType: "html",   //expect html to be returned
        data: {
            lang: lng,
            last_id: last_id,
            ids: dataN
        },
        success: function(response){

            var content = document.getElementById("responsecontainer");
            content.innerHTML = content.innerHTML+response;

            //$("#responsecontainer").html(response);
            $('#more-news').attr('data-lim', Number($('#more-news').attr('data-lim')) + 10);
            //alert(response);
        }

    });
});
<div id="responsecontainer"></div>

            <div style="text-align: center;">
                <button id="more-news" data-lim="10" style="border:none" class="btn-type-one">
                    <span class="more"><?= $this->trans->t('More'); ?></span>
                </button>
            </div>
            


<?php
$dtTTNews = [];
foreach ($front_page_news as $item) {
$dtTTNews[] = $item['id'];
?>
<? } ?>

<script>

    var dataN = <?php echo json_encode($dtTTNews); ?>;
    var lng = '<?=$lang?>';
    var last_id = '<?=end($dtTTNews)?>';

</script>

PHP:

$ids = $_GET['ids'];

$dtNow = new \DateTime('now');

$db->set_charset("utf8");

$news_id = abs($db->real_escape_string($_GET['last_id']));

$date_now = new \DateTime('now');

$in = join(',', array_fill(0, count($ids), '?'));
//$q = $db->query("select * count(*)

$q = $db->query('SELECT * FROM news WHERE id < "'.$news_id.'" ORDER BY date_show DESC LIMIT 3');

//$q = $db->query('SELECT id, title_ru, title_md, body_ru, body_md, is_video, thumb_ru, thumb_md, date_show,title_ru, title_md
//FROM news GROUP BY id');

$lang = (isset($_GET['lang']) && $_GET['lang'] == 'ru') ? 'ru' : 'md';

$isHidden = false;

if($q->num_rows > 0):
    while($item = $q->fetch_assoc()):
        $dtNews = new \DateTime($item['date_show']);


        if ($dtNews > $dtNow) {
            $isHidden = true;
            break;
        }


        $qs = $db->query("SELECT * FROM news_categories WHERE news_id = " . $item['id']);
        if($qs->num_rows > 0) {
            $dd = $qs->fetch_assoc();



            $qss = $db->query("SELECT * FROM categories WHERE id = " . $dd['categories_id']);
            $dd2 = $qss->fetch_assoc();


            if(in_array('Скрытые новости', $dd2) || in_array('Hidden News', $dd2)) {
                $isHidden = true;
                break;
            }

        }

        $dtShow = $dtNews->format("Y-m-d");
        //$dtShow = \Noitools\Utils::timeFromPost($item['date_show'], $lang);


        if($item['active'] == '1'):
            if($item['body_' . $lang] != ''):
                if(!$isHidden):
?>

        <div class="article-item" data-news="<?= $item['id']; ?>">
            <a href="/<?=$lang?>/news_id/<?=$item['id']?>"
               class="link-img-wrap<?= ($item['is_video']) ? ' video-icon-medium' : ''; ?>">
                <img src="/uploads/newsthumbs/760_500/<?=$item['id']?>.jpg"
                     alt="">
            </a>
            <div class="details-post">
                <i><?=$dtShow?></i>

                <a href="news_cat/<?= $dd2['id'] ?>" class="standard-hover-link"><?= $dd2['title_' . $lang] ?></a>;


            </div>
            <h3><a href="/<?=$lang?>/news_id/<?=$item['id']?>"><span
                        class="detail-title"><?=$dtShow?></span> <?= $item['title_' . $lang] ?></a></h3>
            <p class="small-text">
                <?= mb_substr(strip_tags($item['body_' . $lang]), 0, 180,
                    'utf-8') ?>
            </p>
        </div>



<?php  endif; endif; endif; endwhile; endif; ?>

我如何修复此重复项?我想,因为LIMIT 3,当我点击按钮时他加载了3个相同的元素..

我希望当我点击按钮时,再加载3个新闻

1 个答案:

答案 0 :(得分:0)

乍一看似乎问题在于你的SQL语句:

$q = $db->query('SELECT * FROM news WHERE id < "'.$news_id.'" ORDER BY date_show DESC LIMIT 3');

由于您每次都要附加Ajax结果,因此您只想获取之前未提取的新闻结果。通过使用小于,您每次都会获取少于$ news_id的所有结果。

您需要做的是窗口结果。换句话说,您需要有一个起始ID,然后再获取几个记录。所以:

$q = $db->query('SELECT * FROM news WHERE id > "'.$news_id.'" ORDER BY date_show DESC LIMIT 3');

只要你继续传递新的id(你的javascript中的last_id),就像最后一条记录一样,它应该可以工作。

您可能遇到的另一个问题是您的订购。您需要以与比较相同的方式订购。如果按id进行比较,则需要:

$q = $db->query('SELECT * FROM news WHERE id > "'.$news_id.'" ORDER BY id ASC LIMIT 3');

如果按日期比较,那么类似:

$q = $db->query('SELECT * FROM news WHERE date_show < "'.$date_show.'" ORDER BY date_show DESC LIMIT 3');

你不能混合使用id和date_show。除非你知道id和date_show严格按照相同的顺序。