How to load data while scrolling down the page

3.3k Views Asked by At

I'd like to show a list of values that were read from database and will be shown by display tag of Struts to the user, that list of values should be loaded at the same time user scrolls down the page.

My problem is:

As I already have an action that loads just only a few data, now I was thinking of doing the load using $.ajax() function of jQuery, but before trying something like that, I would like to know if there is an option of doing that using other Struts tag or something. (I'm using display tag just because I need sorting.)

1

There are 1 best solutions below

0
On

Loading data on scroll isn't so complicated using jQuery Ajax. Below is the code used to demonstrate scroll event via calling $.ajax() to load data from the Struts action which returns additional content at the end of the scrollbar thumb. Credits to the author of the article Load Data From Server While Scrolling Using jQuery AJAX.

LoadDataAction.java:

@Action(value="load-on-scroll-example", results = {
  @Result(location = "/LoadData.jsp")
})
public class LoadDataAction extends ActionSupport {
  private static int COUNT = 6;

  private InputStream inputStream;

  //getter here
  public InputStream getInputStream() {
    return inputStream;
  }

  @Action(value="load-data", results = {
    @Result(type="stream", params = {"contentType", "text/html"})
  })
  public String loadData() throws Exception {
    String resp = "";
    Map<String, Object> session = ActionContext.getContext().getSession();
    int counter = session.get("counter")== null?COUNT:(int)session.get("counter");
    for(int i = 0; i <= 10; i++) {
      resp += "<p><span>"  + counter++ +
        "</span> This content is dynamically appended " +
        "to the existing content on scrolling.</p>" ;
    }
    session.put("counter", counter);
    inputStream = new ByteArrayInputStream(resp.getBytes());
    return SUCCESS;
  }
}

LoadData.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ taglib prefix="s" uri="/struts-tags"%>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Demo page: Load data while scrolling using Struts2 and JQuery</title>


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script type="text/javascript">
  $(document).ready(function(){
    $contentLoadTriggered = false;
    $("#mainDiv").scroll(function() {
      if($("#mainDiv").scrollTop() >= ($("#wrapperDiv").height() - $("#mainDiv").height()) && $contentLoadTriggered == false) {
        $contentLoadTriggered = true;
        $.ajax({
          url: "<s:url action='load-data'/>",
          success: function (data) {
            $("#wrapperDiv").append(data);
            $contentLoadTriggered = false;
          },
          error:  function (x, e) {
            alert("The call to the server side failed. Error: " + e);
          }
        });
      }
    });
  });

</script>

<style type="text/css">
  body {
    font-family:Arial;
    font-size:.93em;
  }

  #mainDiv {
    background-color:#FAFAFA;
    border:2px solid #888;
    height:200px;
    overflow:scroll;
    padding:4px;
    width:700px;
  }

  #mainDiv p {
    border:1px solid #EEE;
    background-color:#F0F0F0;
    padding:3px;
  }

  #mainDiv p span {
    color:#00F;
    display:block;
    font:bold 21px Arial;
    float:left;
    margin-right:10px;
  }
</style>

</head>
<body>
<form id="form1">
  <div>
    <h1>
      Demo page: Load data while scrolling with Struts2 and JQuery</h1>
    <p></p>
    <p style="margin: 20px 0; background-color: #EFEFEF; border: 1px solid #EEE; padding: 3px;">
      This page is a demo for loading new content from the server and append the data
            to existing content of the page while scrolling.
    </p>
  </div>
  <div id="mainDiv">
    <div id="wrapperDiv">
      <p>
        <span>1</span> Static data initially rendered.
      </p>
      <p>
        <span>2</span> Static data initially rendered.
      </p>
      <p>
        <span>3</span> Static data initially rendered.
      </p>
      <p>
        <span>4</span> Static data initially rendered.
      </p>
      <p>
        <span>5</span> Static data initially rendered.
      </p>
    </div>
  </div>
</form>
</body>
</html>