Ajax應用案例之MSN Space
來源:互聯網
上載者:User
ajax 我一直很推崇MSN Space的服務,對其相簿服務和皮膚一直情有獨鐘。國內的播客,我首選MSN Space。也可能,MSN Space沒有那麼多炒作。
恩,言歸正傳。幾天來研究一下MSN Space的Ajax應用。典型的,其應用主要體現在:網路日誌的評論、固定連結、引用記錄、自訂欄表上面。瞭解Ajax之前,一直對其資料的擷取方式很好奇。現在,大概略知一二了。如下圖所示。
對於共用空間首頁,“添加評論”、“閱讀評論”、“固定連結”、“引用”主要用到的Javascript函數為:OpenSection(section, entryid, bNewComment, bTriedPassportRefresh, bAreNewCommentsAllowed) ,其通過第一個參數section判斷各種操作類別,然後從伺服器擷取資料,在顯示在相應的DIV浮動層中。
其使用Ajax擷取資料的關鍵代碼由Javascript函數GetBlogActivity(entryid, item, otherformfields, bTriedRefresh) 提供。其代碼如下所示:
function GetBlogActivity(entryid, item, otherformfields, bTriedRefresh)
{
var response = "";
var fException = false;
eval (’try {xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {xmlhttp = null;}’);
if (xmlhttp != null)
{
try{
xmlhttp.Open("POST", BlogJSPostUrl, false);
var strA = "handle="+ entryid;
strA += "&blogitem=" + item;
strA += "&" + BlogJSBlogPartParam;
strA += otherformfields;
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.Send(strA);
}catch(e){
fException = true;
}
if(fException){
if(bTriedRefresh){
//exception after trying passport refresh, stop here to avoid infinite loop
response = "error";
}else{
//build the response - an iframe that will load up and refresh passport credentials
var timer = setTimeout(DisplayContentLoadError(item, entryid), 10000); //fail in 10s if not cleared
var iframeString = "<iframe src=\"/PassportRefresh.aspx?id=" + entryid + "&function=get&timer=" + timer + "&item=" + item + "&formfields=" + otherformfields.replace(/&/g, "%26") + "\" />";
var divID = "ppRefresh" + item + entryid;
if(document.getElementById(divID)){
response = iframeString;
document.getElementById(divID).style.display = "none";
}else{
response = "<div style=\"display:none\" id=\"" + divID + "\">" + iframeString + "</div>";
}
}
}else{
if(xmlhttp.status != 200){
response = "error";
}else{
response = xmlhttp.responseText;
}
}
}
return response;
}
很容易看到,其使用了XMLHttpRequest的同步請求方式。這就是為什麼每次單擊“閱讀評論”的時候頁面都需要停頓一下。 xmlhttp.Open("POST", BlogJSPostUrl, false);中所用到的BlogJSPostUrl定義在共用空間的首頁,其餘上述兩個函數定義在BlogJS.js檔案中。
《Ajax開發詳解》的“類比MSN Space”一章將有更加詳細的闡述。