AJAX
Javascript runs on the client (i.e. in the web browser) yet is static text that
is downloaded as part of a web page. Because Javascript is executable code,
web pages with Javascript enhancements can behave more like traditional
software applications than simple static information pages. One of the more
powerful Javascript directives can pull information from a website or service
to change part of the current page - without reloading the whole page.
This feature is often called AJAX (Asynchronous Javascript and XML). Here's an
example.
<html>
<head>
<title>DIV XMLHTTP example</title>
</head>
<body>
<button id="mybutton">Make a request</button>
<button id="myreset">Reset</button>
<div id="mydiv" style="border: solid; margin: 1em;">Show this text when this page is first loaded</div>
<script type="text/javascript">
var http_request = false;
function makeRequest(url) {
if (window.XMLHttpRequest) { // Mozilla, Safari, IE7...
http_request = new XMLHttpRequest();
}
else if (window.ActiveXObject) { // IE6 and older
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}
http_request.onreadystatechange = alertContents;
http_request.open('GET', url, true);
http_request.send(null);
}
function alertContents() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
document.getElementById('mydiv').innerHTML = http_request.responseText;
}
else {
alert('There was a problem with the request.');
}
}
}
document.getElementById('mybutton').onclick = function() {
makeRequest('get-rich-content.html');
}
document.getElementById('myreset').onclick = function() {
document.getElementById('mydiv').innerHTML = 'Show this text on reset';
}
</script>
</body>
</html>
DOM
Sample code for traversing structure of elements that comprise a HTML
page Document Object Model (DOM).
Here is an example.
test = new Array; // unlike simple variables, array are passed to functions by refernce
test[0] = 0; // nest depth
test[1] = 1; // continue recusion
traverse(window.document, test);
function traverse(node) {
var res;
var text;
text = 'nest: ' + test[0] + '\nnode type: ' + node.nodeType + '\nname: ' + node.nodeName;
if (node.nodeType == 3) {
text += '\n' + node.nodeValue.substring(0, 63);
if (node.nodeValue.length > 64)
text += ' ...';
}
res = window.confirm(text);
if (!res)
test[1] = 0;
if (test[1] && node.childNodes != null) {
test['0']++;
for (var i=0; i < node.childNodes.length; i++) {
if (test[1])
traverse(node.childNodes.item(i));
}
test['0']--;
}
}