Ajax请求在php循环中加载下一段数据

时间:2017-09-14 10:43:29

标签: php ajax

我正在将最新的新闻文章加载到我的主页,我想在点击按钮时加载下一篇文章。但是我在点击时收到此错误:home.php:353 Uncaught ReferenceError:未定义nextNews。我写的代码将加载另一篇文章但不会隐藏前一篇文章。对此也有任何建议。

<script>

$( document ).ready(function() {
    var newsCount = 1;
    function nextNews(item){
       newsCount = newsCount + 1;
        $("#newsHome2").load("load-news.php", {
          newsNewCount: newsCount
       });
      }
    });

</script>

 <?php

      $query = $handler->query('SELECT * FROM articles LIMIT 1');
      $results = $query->fetchAll(PDO::FETCH_ASSOC);
       if ($_GET['sort'] == 'dateTime')
       {
           $sql = " ORDER BY dateTime";}
      for ($i=0; $i < count($results); $i++) { 

        echo '<div class="col-lg-6 col-xs-12 col-sm-12      height-news82" id="newsHome2">';
        echo '<h2 class="ashu">Lastest News</h2><br>';
        echo '<p class="news-title78">'.$results[$i]['headline'].'     <br>'.'</p>';
        echo '<img class="news-img33" src="data:image/png;base64,'     .base64_encode( $results[$i]['logo'] ).'"/>';
        echo '<p class="news-time">'.$results[$i]['dateTime'].'<     br>'.'</p>';
        echo '<p class="news-body56">'.$results[$i]['text'].'</p>'     ;
              echo '</p><br><a href="news.php"><button      id="solo-buttons67">Read More</button></a>';
        echo '<i id="arrow20" class="fa fa-chevron-left fa-1x"></     i><i id="arrow21" onclick="nextNews(this)" class="fa      fa-chevron-right fa-1x"></i></div>';
     }
 ?>

2 个答案:

答案 0 :(得分:0)

您的功能&#39; nextNews&#39;在传递给.ready()的匿名函数中定义。所以它不能在你的html中调用。

替代:

  • 使用jquery click event
  • 定义匿名函数之外的函数

答案 1 :(得分:0)

试试这个锻炼它的工作正常:)

查看文件view.php

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>

<div id="newsHome2"></div>

<script type="text/javascript">

var newsCount = 1;

$( document ).ready(function() {
    nextNews(newsCount)
});

function nextNews(newsCount){
       newsCount = newsCount + 1;
        $.post("load-news.php", { newsNewCount: newsCount }, function(data, status){
        $("#newsHome2").html(data);
      });
}
</script>

php file load-news.php

<?php 

if(isset($_POST['newsNewCount'])) { $newsCount=$_POST['newsNewCount']; } else { $newsCount=1; }

echo '<div class="col-lg-6 col-xs-12 col-sm-12      height-news82" id="newsHome2">';
echo '<h2 class="ashu">Lastest News</h2><br>';
echo '<p class="news-title78">headline  '.$newsCount.'   <br>'.'</p>';
echo '<img class="news-img33" src="data:image/png;base64,"/>';
echo '<p class="news-time">dateTime '.$newsCount.'<     br>'.'</p>';
echo '<p class="news-body56">text '.$newsCount.'</p>'     ;
echo '</p><br><a href="#"><button      id="solo-buttons67">Read More '.$newsCount.'</button></a>';
echo '<i id="arrow20" class="fa fa-chevron-left fa-1x"></     i><i id="arrow21" onclick="nextNews('.$newsCount.')" class="fa      fa-chevron-right fa-1x"> click here for next </i></div>';


 ?>