如何用ajax显示页面? [英] How to display the page with ajax?

查看:63
本文介绍了如何用ajax显示页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

即使在页面上我添加了一个过滤器可以对更多行进行分页,我的分页仍然可以正常工作.也就是说,通过该过滤器我可以显示10或50行.

I have a pagination that works correctly even I have added a filter to paginate more rows on the same page is to say that through the filter I can show 10 or 50 rows.

我的代码中的一个小缺陷是重新加载页面,更改了显示的行数,并且在分页按钮中也发生了同样的事情.

The small defect that I have in my code is that the page is reloaded, changing how many rows show and the same happens in the buttons of the pagination.

这是我的代码,所有内容都在同一页面上运行. index2.php .

This is my code, everything is working on the same page index2.php.

<div id="wrapper">
    <div class="container">
        <div id="news-header" class="bootgrid-header container-fluid">
            <div class="row">
                <div class="col-sm-12 actionBar">
                    <div class="search-bar">
                        <input type="text" id="myInput" onkeyup="myFunction()" placeholder="What are you looking for?">
                    </div>
                    <div class="actions btn-group">
                        <?php
                            $select_quantity = '';
                            if (isset($_POST['amount_show'])) :
                                $select_quantity = $_POST['amount_show'];
                            endif;
                        ?>
                        <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
                            <select id="amount_show" name="amount_show" onchange="this.form.submit()">
                                <option value="10" <?php if ($select_quantity==10) echo "selected"; ?>>10</option>
                                <option value="25" <?php if ($select_quantity==25) echo "selected"; ?>>25</option>
                                <option value="50" <?php if ($select_quantity==50) echo "selected"; ?>>50</option>
                                <option value="100" <?php if ($select_quantity==100) echo "selected"; ?>>100</option>
                            </select>
                        </form>
                    </div>
                </div>
            </div>
        </div>
        <?php
            if (isset($_GET['page'])) :
                $page = $_GET['page'] ?: '';
            else :
                $page = 1;
            endif;

            if (isset($_POST['amount_show'])) :
                $records_by_page = $_POST['amount_show'];
            else :
                $records_by_page = 10;
            endif;

            $localization_sql = ($page-1) * $records_by_page;

            $sql = "SELECT id,title,description
                    FROM news
                    ORDER BY id DESC LIMIT $localization_sql, $records_by_page";
            $stmt = $con->prepare($sql);
            $stmt->execute();
            $stmt->store_result();
            if ($stmt->num_rows>0) :

            echo '<table id="myTable" class="table table-condensed table-hover table-striped bootgrid-table">
            <thead>
                <tr>
                    <th>Id</th>
                    <th>Title</th>
                    <th>Description</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>';

            $stmt->bind_result($id,$title,$description);
            while ($stmt->fetch()) :
                echo '<tr>
                    <td>'.$id.'</td>
                    <td>'.$title.'</td>
                    <td>'.$description.'</td>
                    <td>Edit</td>
                </tr>';
            endwhile;
            echo '</tbody>';
            echo '</table>';
            $stmt->close();


            $sql = "SELECT * FROM news";
            $stmt = $con->prepare($sql);
            $stmt->execute();
            $stmt->store_result();

            $BD_records = $stmt->num_rows;
            $stmt->close();
            $con->close();

            $total_page = ceil($BD_records / $records_by_page);
            $prev = $page - 1;
            $next = $page + 1;
            echo '<div class=pagination>
            <ul class="pagination">';
            if ($prev > 0) :
                echo "<li><a href='index2.php?page=1'><i class='icon-angle-double-arrow'></i></a></li>";
                echo "<li><a href='index2.php?page=$prev'><i class='icon-angle-left'></i></a></li>";
            endif;

            for ($i=1; $i<=$total_page; $i++) :
                if ($page==$i) :
                    echo "<li><a class=active>". $page . "</a></li>";
                else :
                    echo "<li><a href='index2.php?page=$i'>$i</a></li>";
                endif;
            endfor;


            if ($page < $total_page ) :
                echo "<li><a href='index2.php?page=$next'><i class='icon-angle-right'></i></a></li>";
                echo "<li><a href='index2.php?page=$total_page'><i class='icon-angle-double-right'></i></a></li>";
            endif;

            echo '</ul></div>';

            else :
                $stmt->close();
            endif;

        ?>
    </div>
</div>

在网上搜索时,我发现了一个ajax代码,但真诚的是,我没有管理使用ajax或javascript/jquery代码.

While searching the web I found an ajax code, but sincerely, I did not manage the use ajax or javascript / jquery code.

您可以解释如何实现此ajax代码或如何避免重新加载页面的小缺陷.

You can explain how to implement this ajax code or how to avoid the small defect of reloading the page.

<script type="text/javascript">
$(document).ready(function() {  
    $('.pagination li a').on('click', function(){
        /*$('.items').html('<div class="loading"><img src="images/loading.gif" width="70px" height="70px"/><br/>Loading...</div>');*/
        $('.items').html('<div class="loading">Loading...</div>');

        var page = $(this).attr('data');        
        var dataString = 'page='+page;

        $.ajax({
            type: "GET",
            url: "ajax.php",
            data: dataString,
            success: function(data) {
                $('.items').fadeIn(2000).html(data);
                $('.pagination li').removeClass('active');
                $('.pagination li a[data="'+page+'"]').parent().addClass('active');

            }
        });
        return false;
    });              
});    
</script>

这是我的代码的工作方式,如下图所示:

This is how my code works, as shown in the following image:

推荐答案

让我们开始重新加载页面的原因:默认浏览器操作.几个html元素会导致浏览器离开当前页面.在这种情况下,我们关注的是:

Let's start with the reason that causes your page to reload: The default browser actions. Several html elements cause the browser to navigate away from the current page. The ones we are concerned in this case are:

  • #amount_show form 提交( onchange 函数),该提交通过 POST 请求发送新值.
  • 分页器本身(带有 a 链接)告诉php脚本通过 GET 请求检索哪些记录.
  • #amount_show form submission (the onchange function) that sends the new value via POST request.
  • The paginator itself (with a links) that tells the php script which records to retrieve via GET request.

两个值都应该传递给php脚本,以便它能够返回正确的记录,否则,即使我们选择了其他值, amount 参数也将是php脚本中的默认值.为此,我们必须将 amount 变量的传递更改为 GET 请求.

Both values should be passed to the php script for it to be able to return the correct records, otherwise the amount parameter would be the default in the php script even if we have a different value selected. To be able to do that, we have to change the passing of the amount variable to a GET request.

此外,更改 amount 值时,我们将默认设置为第一页,以避免重新计算页码.因为分页链接可以因此而发生动态变化,所以我不会用javascript处理,而是用php处理,因为我们已经有了模板和计算方法.这将使事情更容易改变.

Also, when changing the amount value we'll default to the first page to avoid recalculating the page number. Since the pagination links can therefore change dinamically, I'm not going to handle them in javascript but in php instead, since we already have a template and the calculations. This will make things easier to change down the line.

让我们首先解决javascript:

Let's tackle the javascript first:

$(document).ready(function() {
    // When we change the value of the select...
    //     evt contains the information about the event: 
    //         element receiving the action, the action itself, etc.

    $('#amount_show').change(function(evt) {
      // Cancel the default browser action
      evt.preventDefault()
      // Get the target url of the form (our php script)
      url = $(this).parent().attr('action')
      // Call the funtion that will be doing the request
      ajaxLoad(url)
    });

    // When we click a pagination link... (Explanation below)
    $('.items').on('click', '.pagination li a', function(evt) {
      evt.preventDefault()
      url = $(this).attr('href')
      ajaxLoad(url)
    });

    // Do the actual request
    function ajaxLoad(url) {
      // How many records do we want to show ?
      query_params = {
        amount_show: $('#amount_show').val()
      };
      // Show an indication that we are working
      $('.items').html('<div class="loading">Loading...</div>')
      $.ajax({
        type: "GET",
        url: url, // Call php, it will default to page 1 if there's no parameter set
        // When calling a link with a page parameter this will be smart
        // enough to append the variable to the query string correctly
        data: $.param(query_params),
        // Handle the data return. In a perfect world, this is always successful
        success: function(data) {
          // Insert the data in the document.
          $('.items').fadeOut('1000', function() { $(this).html(data) }).fadeIn('1000')
        }
      });
    }
  });

$('.items').on('click','.pagination li a',function(evt){附加

The line $('.items').on('click', '.pagination li a', function(evt) { attaches a delegate event listener to the .items element that will respond to the click events received by .pagination li a. The reason to do this instead of attaching directly to the element itself is two-fold:

  • 减少我们必须循环并附加侦听器的元素数量.
  • 处理元素的动态插入.切换内容时,我们将从文档中删除元素以及它们的侦听器.我们将不得不在每次页面加载时再次附加它们,否则,如果没有附加侦听器,它们将返回到默认操作.但是由于此元素不会改变,所以我们不必这样做.

现在使用php.由于您对使用单个文件感兴趣,因此我将四处移动,但(通常)将是您现在拥有的文件.
注意:将所有内容都放在一个页面中可能会让我误解了您的意思.如果这是您要从主索引中包含的部分模板,则必须更改表单的链接目标和操作以指向它,调整一些javascript选择器,然后可以跳过整个ajax请求检查.主要变化:

Now for the php. Since you are interested in using a single file, I'm just going to move things around but it will (mostly) be what you have now.
Note: I may have misunderstood what you mean by having all in a single page. If this is a partial template that you are including from your main index, you'll have to change the link targets and action for the form to point to it, adjust some javascript selectors and you could skip the whole ajax request checking. Main changes:

  • Remove your onchange function call.
  • Change POST parameter to GET parameter.
  • Add a .items span to insert the elements in since it doesn't exist.
  • Determine if a page load is an ajax load or a regular one using X-Requested-With header. An alternative to this is returning a full response anyway and filtering it with jQuery.

<?php
    if (isset($_GET['page'])) :
        $page = $_GET['page'] ?: '';
    else :
        $page = 1;
    endif;

    if (isset($_GET['amount_show'])) :
        $records_by_page = $_GET['amount_show'];
    else :
        $records_by_page = 10;
    endif;

    $localization_sql = ($page-1) * $records_by_page;

    $sql = "SELECT id,title,description
            FROM news
            ORDER BY id DESC LIMIT $localization_sql, $records_by_page";
    $stmt = $con->prepare($sql);
    $stmt->execute();
    $stmt->store_result();

    if ($stmt->num_rows>0) :

        // Start capturing the output
        ob_start();     
    ?>
    <table id="myTable" class="table table-condensed table-hover table-striped bootgrid-table">
        <thead>
            <tr>
                <th>Id</th>
                <th>Title</th>
                <th>Description</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            <?php
                $stmt->bind_result($id,$title,$description);
                while ($stmt->fetch()) :
                    echo '<tr>
                        <td>'.$id.'</td>
                        <td>'.$title.'</td>
                        <td>'.$description.'</td>
                        <td>Edit</td>
                    </tr>';
                endwhile;
                $stmt->close();
            ?>
        </tbody>
    </table>
    <div class=pagination>
    <ul class="pagination">                
            <?php            
              // When requesting an out-of-bounds page, this won't execute resulting in 
              // a blank page with no paginator
              $sql = "SELECT * FROM news";
              $stmt = $con->prepare($sql);
              $stmt->execute();
              $stmt->store_result();

              $BD_records = $stmt->num_rows;
              $stmt->close();
              $con->close();

              $total_page = ceil($BD_records / $records_by_page);
              $prev = $page - 1;
              $next = $page + 1;

              if ($prev > 0) :
                  echo "<li><a href='" . $_SERVER['PHP_SELF'] . "?page=1'><i class='icon-angle-double-arrow'></i></a></li>";
                  echo "<li><a href='" . $_SERVER['PHP_SELF'] . "?page=$prev'><i class='icon-angle-left'></i></a></li>";
              endif;

              for ($i=1; $i<=$total_page; $i++) :
                  if ($page==$i) :
                      echo "<li><a class='page-link active' >". $page . "</a></li>";
                  else :
                      echo "<li><a class='page-link' href='" . $_SERVER['PHP_SELF'] . "?page=$i'>$i</a></li>";
                  endif;
              endfor;

              if ($page < $total_page ) :
                  echo "<li><a class='page-link' href='index2.php?page=$next'><i class='icon-angle-right'></i></a></li>";
                  echo "<li><a class='page-link' href='index2.php?page=$total_page'><i class='icon-angle-double-right'></i></a></li>";
              endif;

              echo '</ul></div>';

              // Get the output into a variable
              $results_table = ob_get_clean();

          else :
              $results_table = "<div>No results found</div>";
              $stmt->close();
          endif;

          if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])) :
              // If is an ajax request, output just the result table and exit
              echo $results_table;
              die;
          endif;
          // Print the whole page if its not an ajax request
      ?>
  <script type='text/javascript' src='//cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js'/>
  <script src='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/js/bootstrap.min.js' />
  <link rel='stylesheet' href='https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css' type='text/css' />
  <div id='wrapper'>
    <div class='container'>
      <div id='news-header' class='bootgrid-header container-fluid'>
        <div class='row'>
          <div class='col-sm-12 actionBar'>
            <div class='search-bar'>
              <input type='text' id='myInput' placeholder='What are you looking for?'>
            </div>
            <div class='actions btn-group'>
              <form action=<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>'>
                <select id='amount_show' name='amount_show'>
                </select>
              </form>
            </div>
          </div>
        </div>
      </div>

      <span class='items'>
        <?php echo $results_table; ?>
      </span>
    </div>
  </div>

为了完整起见,不使用php分隔响应的另一种方法是通过在 ajax success 回调中执行以下操作来过滤jQuery的响应(不再显示淡入淡出):

For completeness, the alternative method without separating the responses with php, is to filter the response with jQuery by doing the following in the ajax success callback (fades omitted):

results_table = $(data).find('.items').html()
$('.items').html(results_table)

这会将来自服务器的响应转换为jQuery对象,并允许照常应用过滤功能.我们提取感兴趣的内容( items 的内容:结果表和分页),然后将其追加到现有页面的 items 容器中.

This converts the response from the server into a jQuery object and allows to apply filtering functions as normal. We extract the content we are interested in (content of items: result table and pagination), then we just append it to the items container on our existing page.

更新:我已经发布了一个简化示例,其中没有与数据库相关的代码这里.我认为从/向编辑器复制和粘贴代码时发生了一些奇怪的事情.

UPDATE: I've posted a simplified example without database-related code here. I think there's something weird going on when copy&paste'ng code from/to the editor.

  • DOM events
  • jQuery ajax and helper functions
  • PHP output buffering
  • Not receiving X_REQUESTED_WITH request header
  • Fade effects in ajax callback

这篇关于如何用ajax显示页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆