AJax架構中主要涉及的技術:
clIEnt: Javascript解析XML, 操縱DOM修改Html頁面,Javascript是“OO”的語言。
server: servlet + dao, 實現service接口即可
下面是clIEnt中主要的代碼:
1。JS中封裝解析XML的代碼,以及實例應用。
Quote
//類的構造,傳入XML文檔和需要處理的標簽名稱
function DataSet(XMLdoc, tagLabel) {
this.rootObj = XMLdoc.getElementsByTagName(tagLabel)
//3個方法
this.getCount = getCount
this.getData = getData
this.getAttribute = getAttribute
}
function getCount(){
return this.rootObj.length
}
function getData(index, tagName){
if (index >= this.count) return "index overflow"
var node = this.rootObj[index]
var str = node.getElementsByTagName(tagName)[0].firstChild.data
return str
}
function getAttribute(index, tagName) {
if (index >= this.count) return "index overflow"
var node = this.rootObj[index]
var str = node.getAttribute(tagName)
return str
}
//如何使用DataSet類
function updateByXML(XMLDoc) {
var employeeDS = new DataSet(XMLDoc,"employee"); //關心的標簽名稱
var count = employeeDS.getCount()
for(i=0;i<count;i++) {
var name = employeeDS.getAttribute(i,"name")
var job = employeeDS.getData(i,"job")
var salary = employeeDS.getData(i,"salary")
alert(name + "," + job + "," + salary)
}
//使用的XML格式,類似如下
<?XML version="1.0" encoding="gb2312"?>
<employees>
<employee name="Billgates">
<job>Programmer</job>
<salary>32768</salary>
</employee>
<employee name="王濤">
<job>無業游民</job>
<salary>70000</salary>
</employee>
<employee name="Big 中華">
<job>哈爾濱CEO</job>
<salary>100000</salary>
</employee>
</employees>2。操縱DOM,創建table,顯示獲得的數據
Quote
function deleteOldTable() {
delRow = document.getElementsByTagName("table").length
//此句僅在本例中使用,因為本例中已經有一個table了,因此不能刪除,需要根據情況變化一下2005.11.17
if(delRow == 1) return
var node = document.getElementsByTagName("table")[delRow-1]; //表格
var c = node.childNodes.length
for(i=0;i<c;i++)
node.removeChild(node.childNodes[0]); //刪除全部單元行
}
//傳入DataSet的一個實例即可
function makeTable(m_ds) {
deleteOldTable() //先清除以前的結果
var table = document.createElement("table");
table.setAttribute("border","1");
table.setAttribute("width","100%");
document.body.appendChild(table);
var header = table.createTHead();
var headerrow = header.insertRow(0);
headerrow.insertCell(0).appendChild(document.createTextNode("姓名"));
headerrow.insertCell(1).appendChild(document.createTextNode("職業"));
headerrow.insertCell(2).appendChild(document.createTextNode("工資"));
for(var i=0;i<m_ds.getCount();i++) {
var name = m_ds.getAttribute(i,"name")
var job = m_ds.getData(i,"job")
var salary = m_ds.getData(i,"salary")
var row = table.insertRow(i+1);
row.insertCell(0).appendChild(document.createTextNode(name));
row.insertCell(1).appendChild(document.createTextNode(job));
row.insertCell(2).appendChild(document.createTextNode(salary));
}
}