Posted on 2006-02-23 14:52
BlueO2 阅读(334)
评论(0) 编辑 收藏 所属分类:
AJAX
为AJAX贴贴脸系列文章。第一篇为
AJAX贴贴脸之入门篇。本示例部分操作利用了prototype类库,
相关知识请查阅示例为我们以前经常遇到过的动态列表问题,当选择一个下拉框的时候,另外一个的数据将动态产生。
这是个极其简单的应用。不过我们讲由简入繁,最后的示例会展现Google Suggest类型的自动提示。而且我们会不停的对整个示例重构,标题的1-1也表明有1-2等。
1-1是完全自己处理AJAX的各种问题,1-2预计引入其他类库来操作XML,1-3预计用buffalo完成此示例。之后每个示例如果有必要都会有此类对比。由于代码很简单并且有注释,所以文章以代码即可展现应用。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title> Dynamic List </title>
<meta name="Generator" content="EditPlus">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<script src="./script/prototype.js"></script>
<script>
var xmlHttp; //XHR Object
function refreshBookList() {
var bookCate = $F('bookCate');
//clear Books select box
if(bookCate == ""){
clearBookList();
return;
}
//we use XML file directly for demonstrating.
//In real application,you should generate *.xml file by server side
var url;
if(bookCate == "SAP"){
url = "./SAP.xml";
}else {
url = "./SIEBEL.xml"
}
var pars = "";
//Create a new XHR object
xmlHttp = new Ajax.Request(url,{method: 'get',onComplete: handleListChange});
}
//remove list values of select box
function clearBookList() {
var books = $('bookList');
while(books.childNodes.length >0){
books.removeChild(books.childNodes[0]);
}
}
//callback function
function handleListChange(originalRequest){
clearBookList();
var books = $('bookList');
var results = originalRequest.responseXML;
var option = null;
var booksXML = results.getElementsByTagName("books")[0];
for(var i = 0; i < booksXML.childNodes.length;i++){
//get book tag
var listItem = booksXML.childNodes[i];
option = document.createElement('option');
option.appendChild(document.createTextNode(listItem.firstChild.nodeValue));
books.appendChild(option);
}
}
</script>
</head>
<body>
<form action="#">
Book Categroies:
<select name="bookCate" id="bookCate" onchange="refreshBookList();">
<option>Select One</option>
<option value="SAP">SAP Books</option>
<option value="SIEBLE">SIEBEL Books</option>
</select>
<br/><br/>
<select name="bookList" id="bookList" size="6" style="width:300px"></select>
<br/>
</form>
</body>
</html>
SAP.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<books>
<book>
ABAP
</book>
<book>
BW
</book>
<book>
FI module
</book>
</books>
SIEBEL.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<books>
<book>
SIEBEL
</book>
<book>
CRM
</book>
</books>