-Microsoft
first introduced the XMLHTTPRequest object, implementing it in Internet
Explorer 5 as an ActiveX object.
- The
following line creates an XMLHTTPRequest object called request
var request = new XMLHTTPRequest();
- Here we have declared a variable request and assigned to it the value returned from the statement
new XMLHTTPRequest(),which is invoking the constructor method for the XMLHTTPRequest object.
- To achieve the equivalent result in Microsoft Internet Explorer, you need to create an ActiveX object.
Here's an example
var request = new ActiveXObject("Microsoft.XMLHTTP");
- This assigns the name request to the new object.
- Some versions of Internet Explorer have a different version of MSXML, the Microsoft XML parser,
installed in those cases you need to use the following instruction
var request = new ActiveXObject("Msxml2.XMLHTTP");
- For cross Browser detection, this is the following code :
function ajaxFunction()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
alert("Your browser does not support XMLHTTP!");
}
}
In above example create a variable named xmlhttp to hold the XMLHttpRequest object,
Try to create the XMLHttpRequest object with xmlhttp=new XMLHttpRequest(). If that fails,
try xmlhttp=new ActiveXObject("Microsoft.XMLHTTP").
This is for IE6 and IE5. If that fails too, the user has a very outdated browser,
and will get an alert stating that the browser doesn't support XMLHTTP.
Note: The code above
can be used every time you need to create an XMLHttpRequest object.
ajaxdemo.html
<script
type="text/javascript">
var http =
false;
if(navigator.appName
== "Microsoft Internet Explorer")
{
http
= new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
http = new XMLHttpRequest();
}
function replace()
{
http.open("GET", "test.txt", true);
http.onreadystatechange=function()
{
if(http.readyState == 4)
{
document.getElementById('changed').innerHTML
= http.responseText;
}
}
http.send(null);
}
</script>
<p><a
href="javascript:replace()">Replace Text</a></p>
<div
id="changed">
Hello,
world!
</div>
test.txt
This is the
content of test.txt