Dag Sunde wrote:
SE wrote: I have killed the last three lines and made a couple
of other changes and it is working now. Thanks for
your help. I will now get down to the real programming!
Good!
You can also make it cleaner/easier to read (IMO) by
separating the onreadystatecha nge function in a separate
function:
var xmlhttp;
function getTest() {
xmlhttp = new XMLHttpRequest( );
xmlhttp.open("G ET", "test.txt",true );
xmlhttp.onready statechange = testCallback;
xmlhttp.send(nu ll);
}
function testCallback() {
if (xmlhttp.readyS tate==4) {
if (xmlhttp.status ==200)
alert("URL Exists!");
else if (xmlhttp.status ==404)
alert("URL doesn't exist!");
else
alert("Status is "+xmlhttp.statu s);
}
}
It is an opinion that you won't maintain after you have thought about it
a bit.
Asynchronous XmlHttp requests may be concurrent, that is, a second may
be initiated before the completion of the first. If you use a single
globally scoped variable to hold a reference to an XmlHttp request
object then the initiation of the second request replaces the reference
to the first object. If this happens before the first request has fully
loaded its onreadystatecha nge handler will be reading the readyState of
the second request whenever the state of the first changes. This will
almost certainly mean that it never does whatever it was intended to do.
And in the event that coincidence does have it act (a readyState change
happens in the first object when the second object is already at
readyState 4) it will be acting upon the wrong XmlHttp request object.
Unfortunately the possibility of having the event handling function act
upon its own object through the use of the - this - keyword is rendered
non-viable by a bug in IE that prevents the correct resolution of the -
this - keyword in the context of the onreadystatecha nge handler.
This situation is normally coped with through the use of closures, and
so assigning an inner function to the event handler is normal and
sensible. Subject to that reference being freed after the completion of
the process to avoid circular references causing the IE memory leak
problem. But your global reference to the object leaves an un-freed
circular reference anyway (The function object refers to its scope
chain, its scope chain refers to the global object, the global object
refers to the XmlHttp request object (as the value of its xmlhttp
property), the XmlHttp request object refers back to the function object
(as the value of its onreadystatecha nge property)).
Richard.