The _options object gets a timeout variable, which defines how many seconds
you should wait before giving up on the request. The _options object also loses its callback
property that gets replaced with onerror() and onsuccess() functions.
function checkForTimeout()
{
if(transport.readyState != 4)
{
aborted = true;
transport.abort();
}
}
setTimeout(checkForTimeout, _options.timeout * 1000);
A function is set up, which you??™ll call after the timeout period to see whether the object
has successfully returned. If it hasn??™t, set the aborted variable to true to indicate that you manually
had to end this call; you use the abort method on the XHR object. Doing so will automatically
execute the onreadystatechange event handler.
CHAPTER 5 n AJAX AND DATA EXCHANGE 121
function onreadystateCallback()
{
if(transport.readyState == 4)
{
if( !aborted && transport.status >= 200 && transport.status < 300 )
{
_options.onsuccess(transport);
}else{
_options.onerror(transport);
}
}
}
transport.open(_options.method, url, true);
transport.onreadystatechange = onreadystateCallback;
transport.send();
The onreadystateCallback() function handles the onreadystatechange event. Within the
onreadystateCallback() function, check the status and dispatch to either the onsuccess or the
onerror event handlers accordingly. I check to see whether the call was aborted manually and
then whether the HTTP status code is between 200 and 300, which indicates a successful call.
Pages:
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189