Handling Live Web Content in WSH - Part 2 - Implementing a Workaround
(Page 5 of 6 )
By design, the XMLHttpRequest object has an event called onReadyStateChange for this. However, it isn’t fully supported and doesn’t work with VBScript, so we’ll create our own workaround in the form of a timeout loop after we call the Send() method.
varCounter = 0
Do Until (objxmlHTTP.ReadyState = 4) Or (varCounter = 30)
varCounter = varCounter + 1
Wscript.Sleep(1000)
Loop
We start by creating a counter variable. Then we create a loop that increments our counter. The loop will break out any time our ReadyState indicates that the connection is complete or when approximately 30 seconds have passed. We use the Sleep() method to ensure that each iteration takes approximately one second.
Now we’re ready to set up some conditional statements. We need to first determine whether a timeout error has occurred. If so, we should quit trying to make the connection.
If varCounter = 30 Then
objxmlHTTP.Abort()
result = "Your request has timed out. Please try again later."
We use the XMLHttpRequest object’s Abort() method to stop any transfer attempts and then set the result string variable to notify the user.
Elseif objxmlHTTP.Status <> 200 Then
result = objxmlHTTP.Status & ": " & objxmlHTTP.StatusText
Now we perform a quick check to make sure that no server errors occurred. We can do this by checking that the Status property equals 200 (or OK).
Finally, we can process our results.
Else
result = objxmlHTTP.ResponseText
End If
Our Else statement sets our result equal to the text data returned by the XMLHttpRequest object. We’ll finish by closing the connection (by emptying our object) and echoing the results like we did in the last example.
Here are two example outputs after a timeout error and a server error, respectively.
Your request has timed out. Please try again later.
404: Not Found
I’ve included this workaround into the completely reusable function available in the source code for this article. The code also includes an additional function for providing text-based error codes based on the ReadyState property.
Next: Other Uses for XMLHttpRequest >>
More Windows Scripting Articles
More By Nilpo/Developer Shed Staff Writer