简体   繁体   English

AJAX加载和页面滚动

[英]AJAX load and page scrolling

I need help with the following problem. 我需要以下问题的帮助。 There is a button on my page and the press of the button loads content in a “div” element positioned below the button via AJAX. 我的页面上有一个按钮,按下按钮会通过AJAX将内容加载到位于按钮下方的“ div”元素中。 Everything works fine but one thing. 一切正常,但只有一件事。 The page scrolls a bit with each press of the button but I want it to keep its position. 每按一下该按钮,页面就会滚动一点,但我希望它保持其位置。

Here is my HTML code: 这是我的HTML代码:

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

And here is my JavaScript code (I am using jQuery): 这是我的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());
}

I searched through other posts but didn't find any working solution. 我搜索了其他帖子,但找不到任何有效的解决方案。 Any suggestions would be appreciated! 任何建议,将不胜感激!

I found out where the problem came from. 我找出问题的根源。 Since the content loaded in the “div” element changed its height 2 times with each press of the button, the height of the page body changed as well. 由于每次按下按钮时,加载到“ div”元素中的内容的高度都会发生2倍的变化,因此页面主体的高度也会发生变化。 This was the cause of the scrolling. 这就是滚动的原因。 I fixed the height of the “div” element in the css file: 我固定了css文件中“ div”元素的高度:

div#result {height: 200px;}

This solved the problem. 这样就解决了问题。

Good, for the answer and also good if you give your code in jsfiddle. 很好,对于答案,如果在jsfiddle中提供代码,也很好。 Still no issue, recently I have done the same thing. 仍然没有问题,最近我做了同样的事情。

By default it same position if you click on button, but if you have anchor tag, then it will automatically goes on top. 默认情况下,如果您单击按钮,则其位置相同,但是如果您具有锚标记,则它将自动位于顶部。

There is so many things to stay or scroll on desired position. 有很多东西要停留或滚动到所需的位置。

window.scrollTo(0, 0); 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 http://www.w3schools.com/jsref/prop_loc_hash.asp

Using window.location.hash in jQuery 在jQuery中使用window.location.hash

You have to call this function on page load. 您必须在页面加载时调用此函数。

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>

Implementing with php ie getrecords.php 用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>';
      }
    }
    ?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM