What's AJAX?
Ajax stands for Asynchronous JavaScript and XML.it is the use of the
nonstandard XMLHttpRequest object to communicate with server-side scripts.
It can send as well as receive information in a variety of formats,
including XML, HTML, and even text files.
Ajaxs is asynchronous nature, which means it can do all of this
without having to refresh the page. This allows you to update portions of a
page based upon user events.
The two features in question are that you can:
Make requests to the server without reloading the page
Parse and work with XML documents
A Simple Example How to Make an HTTP Request
A simple HTTP request. Our JavaScript will request an HTML
document, test.html, which contains the text "I'm a test." and then we'll
alert() the contents of the test.html file.
<script type="text/javascript" language="javascript">
function makeRequest(url) {
var httpRequest;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
if (httpRequest.overrideMimeType) {
httpRequest.overrideMimeType('text/xml');
// See note below about this line
}
}
else if (window.ActiveXObject) { // IE
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = function() { alertContents(httpRequest); };
httpRequest.open('GET', url, true);
httpRequest.send('');
}
function alertContents(httpRequest) {
if (httpRequest.readyState == 4) {
if (httpRequest.status == 200) {
alert(httpRequest.responseText);
} else {
alert('There was a problem with the request.');
}
}
}
</script>
<span
style="cursor: pointer; text-decoration: underline"
onclick="makeRequest('test.html')">
Make a request
</span>
|