AJAX加载和页面滚动

4
我可以帮助您翻译以下问题。我的页面上有一个按钮,按下该按钮会通过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());
}

我搜索了其他帖子,但没有找到任何可行的解决方案。欢迎提出任何建议!


尝试在点击事件中添加 event.preventDefault() 和/或 event.stopPropagation() - Jeremy Thille
你也可以在按钮上放置一个锚点,在ajax调用后,使用"scrollTo()"滚动到锚点处? - Jordumus
3个回答

1
我找到了问题所在。由于“div”元素中加载的内容每按一次按钮就会改变两次高度,因此页面主体的高度也会改变。这就是滚动的原因。我在css文件中修复了“div”元素的高度:
div#result {height: 200px;}

这解决了问题。

0

很好,如果你能在 jsfiddle 上提供代码也很好。最近我也完成了同样的事情。

默认情况下,如果单击按钮,它会在相同的位置,但如果你有锚点标签,则它将自动回到顶部。

有很多东西可以停留或滚动到所需的位置。

window.scrollTo(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


0

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

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 实现,即 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>';
      }
    }
    ?>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接