OK, the past couple of blogs were dedicated to introduction to Ajax and an explanation of what it is. Now, we can start getting into the meat of Ajax. In this blog I will explore how to bind data to Html components. I will also look how to use HTML, CSS, and DOM to dynamically create and manipulate components.
Unlike C# or Java, the HTML form components were not originally designed for desktop-like programming models. It does not have the rich set of built-in data models used for data binding that are found in components provided by these traditional languages. However, what JavaScript provides is the Document Object Model (DOM) which is a structured (tree) representation of all the elements that represents an XML document (HTML being an XML doc included).
The document object model for this simple web page is illustrated below. Notice that each tag (element) is a node in the DOM tree. The attributes of each element are also represented in the tree.
function updateParagraph() {
// use convenient DOM to loacate element by ID
var pTag = document.getElementById('paragraphTag');
//programmatically change theelement
pTag.style.backgroundColor="blue";
pTag.style.color="white";
pTag.style.fontWeight="bold";
// remove existingtag child which is the text (see dom tree).
pTag.removeChild(obj.lastChild);
//now, add the new TEXT to theelement
var msg = document.getElementById('name').value + ", this is a DOM Example!"
pTag.appendChild(document.createTextNode(msg));
}
A Document
Document Heading
This is a paragraph tag.
Enter Name:
DOM Tree:
root
|
+ html
|
+ script
| |
| + TEXT: function bindFormData(objId, data) { ...
| ...
+ head
| |
| + title
| |
| + TEXT: A Document
|
+ body
|
+ ATT: bgcolor=yellow
|
+ h1
| |
| + TEXT: Document Heading
|
+ p
| |
| + ATT: style=color:red;font-weight:bold
| |
| + TEXT: This is a paragraph tag.
|
+ form
|
+ TEXT: Enter Name
|
+ input
| |
| + ATT: id=name
| |
| + ATT:size=30
|
+ button
|
+ ATT: value=Click Me
|
+ ATT: onclick=updateParagraph()
DOM Navigation
Using the DOM API developers can traverse (query) and modify node values in the DOM tree. So component declared in the HTML page at design-time can programmatically updated at run-time using the DOM API. Also, using the DOM API, programmers can programmatically add new elements to the DOM tree (at run-time) that was not declared at design-time. One can build entire page programmatically without any prior existence of an HTML page.
In this sample HTML page above, we use the document.getElementById() to locate the node using the node’s id value. This one way of quickly locating a node on the DOM. You can iteratively traverse the tree nodes one by one until you locate a specific node using a loop construct. In future blogs, I will explore how to construct more complicated structures such as tables.
References

