[ 2006-01-20 18:04:32 | Author: greengnn ] Font Size: Large | Medium | Small Quote
轉自:垃圾豬的垃圾窩
原文:http://ewebapp.cnblogs.com/archive/2005/11/24/283492.html
因為最進想學習一下AJAX技術所以貼到這裡方便閱讀
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));
}
}