2009年10月4日 星期日

取得XMLHttpRequest物件

這一段碼,幾乎是非同步傳輸中 javascript 非寫不可的:
(以下內容取自廖信彥先生所著AJAX與JSP整合應用)

/* 取得非同步傳輸物件 */
function createXMLHttp() {
var xhr;
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e1) {
try {
xhr = new XMLHttpRequest();
} catch (e2) {
xhr = null;
} } }
return xhr;
}


/* 開啟檔案 */
function getFile(mime) {
var filename = "sample.xml";
xmlhttp = createXMLHttp();
document.getElementById("disp").innerHTML = "";
if (xmlhttp) {
xmlhttp.overrideMimeType(mime); //指定MIME型別
xmlhttp.onreadystatechange = showMsg;
xmlhttp.open("GET", filename, true);
xmlhttp.send(null); }
}

/* MIME型別 */
'text/xml':讀取XML檔案,以XML格式顯示
'text/html':讀取XML檔案,以HTML格式顯示
'text/plain':讀取XML檔案,以文字檔格式顯示

/* AJAX呼叫 */
function sendRequest() {
var url, parm;
parm = Form.serialize("aForm");
url = "getData.jsp";
var myAjax = new Ajax.Request(
url,
{method: "post", parameters: parm,
onComplete: showMsg}
);
}

/* 顯示訊息 */
function showMsg() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{ document.getElementById("disp").innerHTML = xmlhttp.responseText; } }

/* 顯示訊息,物件為XML格式 */
function showMsg(xmlhttp) {
var xmlDoc = xmlhttp.responseXML;
var chr10 = String.fromCharCode(10); //line feed
//取出"姓名"與"職稱"標記的陣列
var names = xmlDoc.getElementsByTagName("姓名");
var titles = xmlDoc.getElementsByTagName("職稱");
var attName = "nickname";
var result = "";
for (i = 0; i < names.length; i++) {
flag = authors[i].hasChildNodes();
attValue = names[i].getAttribute(attName);
result += names[i].firstChild.nodeValue + attValue + ":";
result += titles[i].firstChild.nodeValue + chr10 ; }
$("tArea").value = result; }

/* 顯示訊息,物件為JSON格式 */
function showMsg(xmlhttp) {
var jsonDoc = xmlhttp.responseText;
eval("var objBooks = " + jsonDoc);
var chr10 = String.fromCharCode(10); //line feed
var result = "";
for (var i = 0; i < objBooks.books.book.length; i++) {
result += objBooks.books.book[i].bookId + chr10;
result += objBooks.books.book[i].title + chr10;
result += objBooks.books.book[i].author + chr10;
result += objBooks.books.book[i].price + chr10;
}
$("disp").innerHTML = result;
}

0 意見: