What is the lifespan of an ajax call?

let's say I have this code in javascript:

function doAnAjaxCall () { var xhr1 = new XMLHttpRequest(); xhr1.open('GET', '/mylink', true); xhr1.onreadystatechange = function() { if (this.readyState == 4 && this.status==200) { alert("Hey! I got a response!"); } }; xhr1.send(null); } 

and let the code in the servlet:

 public class RootServlet extends HttpServlet { public void doGet (HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.getWriter().write("What up doc?"); resp.setStatus(200); } } 

Will xhr1 wait for new readistate changes? Or is he closed as soon as he receives the first answer? If it remains open, will it lead to a memory leak / slow browser after some time and some of them accumulate? Should I always call resp.getWriter (). close () at the end of the servlet code?

And finally, for jQuery fans:

Does $.ajax() like XMLHttpRequest() in this regard?

+6
java javascript jquery ajax servlets
source share
1 answer

Will xhr1 wait for new readistate changes? Or does he close as soon as he receives the first answer? If it remains open, can this lead to a memory leak / slow browser after some time and accumulation of several of them?

Behind the scenes, he remains open. This (and memory usage), however, is responsible for the webbrowser engine. It supports a certain number of connections in the pool, which in any case has a maximum limit on the domain. MSIE, for example, has an error that causes them to leak when they are still working, while the user unloads (closes) the window.

Should I always call resp.getWriter().close() at the end of the servlet code?

Not necessary. The servlet container will close it anyway. Closing it only prevents the risk that some (buggy) code will be further in the response chain, from writing to the body of the response. See this answer for more details.

And finally, for jQuery fans: $.ajax() behaves like XMLHttpRequest() in this regard?

It uses XMLHttpRequest under covers (only with browser support, otherwise it is an MSIE ActiveX object). It creates a new one for each call. Open the uninstalled source code , Ctrl + F is the jQuery.ajaxTransport( function jQuery.ajaxTransport( . The entire ajax processing code is almost 200 loc, and it covers all possible browser bug fixes you might think of.

+5
source share

All Articles