views:

1848

answers:

3
Does anyone know if there is a way to use a single XMLHTTPRequest object to send multiple asynchronous requests. I can do it with a single request and get a response back from my onreadystatechange() handler. I'm wondering if there's a way to use the same object to send multiple parallel requests but I'm not seeing any way to match a response to a request from the onreadystatechange() function.
+9  A: 

Short answer: You can't.

Question you really need to ask yourself is why would you want that over multiple XMLHTTPRequest objects ? There's hardly a downside to instantiating a dozen or so objects.

Martijn Laarman
I agree. I think I may be misunderstanding the xmlhttpRequest abstraction. I've been told I both need to have a framework where multiple http requests may be in flight but that I also need to keep a particular xmlhttprequest around because I had used it to authenticate to a website.
Dan G
Multiple subsequent requests can be made with a single XMLHTTPRequest object. Though it really is much more reliable to create a new one.
davenpcj
True but the question specifically mentions parallel requests and thus my frank response :)
Martijn Laarman
+1  A: 

+1 to Martijn's answer, but I wanted to add that the enlightenment you're missing is that a Request is by definition a one time object.

annakata
A: 

You can reuse the object after the first request completes to issue a second request, and change onreadystatechange to a different function.

Not parallel, but very quick.

A note of caution, IE can't reuse XMLHTTPRequest objects, even in the native XMLHTTP implemented in IE7 and IE8.

For parallel requests, create multiple XMLHTTPRequest objects, and distribute your calls across them.

Another note of caution, when creating multiple objects in parallel, browsers may limit your usage of concurrent XMLHTTPRequest objects. Often in a very bad way by losing requests or transparently refusing to send them, so you'll want to test that carefully.

The safest way to do things is to create one request, use it, then dispose of it and create a new one. One at a time.

davenpcj