Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the life span 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 be:

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

Will xhr1 still wait for new changes in readystate? Or it is closed as soon as it gets the first response? If it remains open, will it lead to memory leaks/slower browser after a while and accumulating a few of those? Should I always call resp.getWriter().close() at the end of the servlet code?

And, lastly, for the jQuery fans out there:

does $.ajax() behave as XMLHttpRequest() in that respect?

like image 336
Aleadam Avatar asked Apr 01 '11 01:04

Aleadam


1 Answers

Will xhr1 still wait for new changes in readystate? Or it is closed as soon as it gets the first response? If it remains open, will it lead to memory leaks/slower browser after a while and accumulating a few of those?

Behind the scenes, it remains open. It (and the memory occupation) is however the responsibility of the webbrowser engine. It maintains a certain amount of connections in a pool which has a maximum limit per domain anyway. MSIE for example has a bug which causes them to leak away when they are still running while the user unloads (closes) the window.

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

Not necessary. The servletcontainer will close it anyway. Closing it yourself only prevents the risk of some (buggy) code further in the response chain from writing to the response body. For more detail, see this answer.

And, lastly, for the jQuery fans out there: does $.ajax() behave as XMLHttpRequest() in that respect?

It uses XMLHttpRequest under the covers (only when supported by the browser; otherwise it's the MSIE ActiveX object). It constructs a new one on every call. Open the unminified source code, Ctrl+F the jQuery.ajaxTransport( function. All the ajax handling code is almost 200 loc and it covers all possible browser specific bug fixes you can think about.

like image 76
BalusC Avatar answered Oct 11 '22 14:10

BalusC