javascript - Ajax response from a servlet is printing twice -
i facing problem while appending content of div using ajax.the response servlet printing twice.
here code both 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 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 page here. may use following sample code. */ out.println("this dynamic text<br>"); } { out.close(); } } }
the final content of output div is:
this static text.
this dynamic text.
this dynamic text.
i unable understand why dynamic text printing twice.
thanks in advance.
i suspect onreadystatechange
being called multiple times, more 1 of carrying response. see what different readystates in xmlhttprequest mean, , how can use them? put breakpoint in handler check.
you want add check response complete:
xhr.onreadystatechange = function() { if (xhr.readystate == 4) { content.innerhtml += xhr.responsetext; } }
Comments
Post a Comment