The first thing you need to do is create an object that you can instantiate. You??™ll want to
make it a reusable class because you??™ll need to instantiate the object with each request you
want to make:
function Ajax()
{
var transport;
if(window.XMLHttpRequest) {
transport = new XMLHttpRequest();
}else{
try{ transport = new ActiveXObject("MSXML2.XMLHTTP.6.0"); }catch(e){}
try{ transport = new ActiveXObject("MSXML2.XMLHTTP"); }catch(e){}
}
if(!transport) return;
this.transport = transport;
}
Ajax.prototype.send = function(url, options)
{
if(!this.transport) return;
var transport = this.transport;
var _options = {
method:"GET",
callback:function(){}
};
// override options
for(var key in options)
{
_options[key] = options[key];
}
transport.open(_options.method, url, true);
transport.onreadystatechange = function(){ _options.callback(transport) };
transport.send();
}
CHAPTER 5 n AJAX AND DATA EXCHANGE 117
In the object constructor, you establish which object you can use. First, you test for the
existence of the XMLHttpRequest object, which is supported in all modern browsers, including
Firefox 1+, Safari 1.2+, Opera 7.6+, and IE 7+. For IE 5 and 6 (or IE 7 users who might have the
native object turned off), try to instantiate the ActiveX versions of the XHR object.
You try to instantiate them in try/catch blocks because IE will generate an alert dialog if
the ActiveX objects are turned off altogether.
Pages:
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184