【问题标题】:AJAX load and page scrollingAJAX 加载和页面滚动
【发布时间】:2015-03-22 17:19:04
【问题描述】:

我需要帮助解决以下问题。我的页面上有一个按钮,按下按钮会通过 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()
  • 你也可以在你的按钮上放一个锚点,在你的ajax调用之后,你“scrollTo()”这个锚点?

标签: javascript jquery html ajax


【解决方案1】:

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

div#result {height: 200px;}

这解决了问题。

【讨论】:

    【解决方案2】:

    很好,对于答案,如果您在 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

    Using window.location.hash in jQuery

    【讨论】:

      【解决方案3】:

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

      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>';
            }
          }
          ?>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多