AJAX加载和页面滚动

AJAX load and page scrolling

本文关键字:滚动 加载 AJAX      更新时间:2023-09-26

我需要帮助解决以下问题。我的页面上有一个按钮,按下该按钮可以通过AJAX加载位于按钮下方的"div"元素中的内容。一切都很好,只有一件事。每次按下按钮,页面都会滚动一点,但我希望它保持原位。

这是我的HTML代码:

<input type="button" name="calculate" value="Calculate"
    onclick="invoke(this.form, this.name, '#result')"/>

这是我的JavaScript代码(我使用的是jQuery):

function invoke(form, event, container) {
    $('input[type="button"]').attr('disabled', 'disabled');
    $(container).html('<br/><div class="img"><img src="/Test/img/ajax-loader.gif"/><div>');
    $(container).load(form.action, event + '&' + $(form).serialize());
}

我搜索了其他帖子,但没有找到任何有效的解决方案。如有任何建议,我们将不胜感激!

我发现了问题的根源。由于每次按下按钮,"div"元素中加载的内容的高度都会更改2次,因此页面主体的高度也会更改。这就是滚动的原因。我修复了css文件中"div"元素的高度:

div#result {height: 200px;}

这解决了问题。

答案很好,如果你用jsfiddle编写代码,也很好。仍然没有问题,最近我也做了同样的事情。

默认情况下,若你们点击按钮,它会处于相同的位置,但若你们有锚标签,那个么它会自动位于顶部。

有太多的东西需要停留或滚动到所需的位置。

window.rollTo(0,0);

    function buttonclick(isfirsttimeload)
    {        
          if (typeof isfirsttimeload!= "undefined")
              window.scrollTo(0, 0);
          else
            location.hash = '#asearchresult'; //this is hidden anchortag's id, which scrolldown on click.
   } 

http://www.w3schools.com/jsref/prop_loc_hash.asp

在jQuery 中使用window.location.hash

您必须在页面加载时调用此函数。

limit – The number of records to display per request.
offset – The starting pointer of the data.
busy – Check if current request is going on or not.
The main trick for this scroll down pagination is binding the window scroll event and checking with the data container height

$(document).ready(function() {
$(window).scroll(function() {
          // make sure u give the container id of the data to be loaded in.
          if ($(window).scrollTop() + $(window).height() > $("#results").height() && !busy) {
            busy = true;
            offset = limit + offset;
            displayRecords(limit, offset);
          }
});
})





<script type="text/javascript">
          var limit = 10
          var offset = 0;
          function displayRecords(lim, off) {
            $.ajax({
              type: "GET",
              async: false,
              url: "getrecords.php",
              data: "limit=" + lim + "&offset=" + off,
              cache: false,
              beforeSend: function() {
                $("#loader_message").html("").hide();
                $('#loader_image').show();
              },
              success: function(html) {
                $('#loader_image').hide();
                $("#results").append(html);
                if (html == "") {
                  $("#loader_message").html('<button data-atr="nodata" class="btn btn-default" type="button">No more records.</button>').show()
                } else {
                  $("#loader_message").html('<button class="btn btn-default" type="button">Load more data</button>').show();
                }
              }
            });
          }
          $(document).ready(function() {
            // start to load the first set of data
            displayRecords(limit, offset);
            $('#loader_message').click(function() {
              // if it has no more records no need to fire ajax request
              var d = $('#loader_message').find("button").attr("data-atr");
              if (d != "nodata") {
                offset = limit + offset;
                displayRecords(limit, offset);
              }
            });
          });
        </script>

用php实现ie getrecords.php

 <?php
    require_once("config.php");
    $limit = (intval($_GET['limit']) != 0 ) ? $_GET['limit'] : 10;
    $offset = (intval($_GET['offset']) != 0 ) ? $_GET['offset'] : 0;
    $sql = "SELECT countries_name FROM countries WHERE 1 ORDER BY countries_name ASC LIMIT $limit OFFSET $offset";
    try {
      $stmt = $DB->prepare($sql);
      $stmt->execute();
      $results = $stmt->fetchAll();
    } catch (Exception $ex) {
      echo $ex->getMessage();
    }
    if (count($results) > 0) {
      foreach ($results as $res) {
        echo '<h3>' . $res['countries_name'] . '</h3>';
      }
    }
    ?>