0

I think my question is odd… I’m learning here, and would like to use AJAX & JSP to display some other JSP pages in order. i.e. click button: page1.jsp displayed, click button again: page2.jsp displayed, …

I got the JSP to add the ‘1’ after page and JSP does increment the variable. But it does not change the value past page 1…

It increments correctly in the function if I do a location.reload(), but that of course brings me back to page one…

I’m sure there are other ways to do this, but I simply want this to work using JSP… Any ideas

    <!DOCTYPE html>
<html>
<head>
<%! int n = 0;%>
<script>

function loadDoc() {
<% n = n+1; %>
var xmlhttp;

if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }

xmlhttp.open("GET","page<%=n%>.jsp",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv"><h2>Using AJAX to display next page</h2></div>
<button type="button" onclick="loadDoc()">Change Page</button>
</body>
</html>

1 Answer 1

1

n is 0 each time. You need to save n. Try using a

<input type="hidden" value="0" id="countvariable" />

in your html somewhere.

Then inside loadDoc() put

var n = 1 + parseInt(document.getElementById("countvariable").value);
document.getElementById("countvariable").value = n;

This should hold your variable. Also, the parseInt is a must otherwise javascript will append the 2 together and you will get 10 as n instead of 1.

Updated: If you want to go back after a certain amount of pages then add this to the end.

if(n == 2)
{
   document.getElementById("countvariable").value = 0;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the quick reply!! I think I see where you’re going, and again I’m learning here… I see this would not work with my JSP specific elements, so I can just drop that idea for now  How do I use that new var n as an argument in the .open()? I swear I tried to look that up, but my question is so basic and the results just don’t have it… ?? how do I get the variable n in here ?? xmlhttp.open("GET","page??n??.jsp",true);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.