I am facing problem while appending the content of a div using ajax.The response from the servlet is printing twice.
Here is the code for both the pages.
demo.jsp
<html>
<head>
<script>
function run()
{
var content = document.getElementById("output");
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
content.innerHTML += xhr.responseText;
}
xhr.open("POST", "demo", true);
xhr.send(null);
}
</script>
</head>
<body>
<input type="submit" value="Add Content" onclick="run();"/>
<div id="output">This is Static Text.</span><br>
</div>
</body>
DemoServlet
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(urlPatterns = {"/demo"})
public class Demo extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
/* TODO output your page here. You may use following sample code. */
out.println("This is Dynamic Text<br>");
} finally {
out.close();
}
}
}
The final content of the output div is:
This is Static Text.
This is Dynamic Text.
This is Dynamic Text.
I am unable to understand why the Dynamic Text is printing twice.
Thanks in advance.