我一直很推崇 MSN Space 的服務,對它的相冊與皮膚設計更是情有獨鍾。說到國內的部落格平台,我也首推 MSN Space——或許是因為它沒有那麼多炒作。言歸正傳,這幾天我研究了一下 MSN Space 的 Ajax 應用,典型的應用主要體現在網路日誌的評論、固定連結、引用通告與自訂清單上。在了解 Ajax 之前,我對它取得資料的方式一直很好奇,現在總算略知一二。
以共享空間首頁為例,「新增評論」、「閱讀評論」、「固定連結」、「引用通告」主要用到的 JavaScript 函式為:
OpenSection(section, entryid, bTriedPassportRefresh, bAreNewCommentsAllowed)
它透過第一個參數 section 判斷各種操作類別,接著從伺服器取得資料,並顯示在對應的 DIV 浮動層中。
而真正用 Ajax 取資料的關鍵,則由 JavaScript 函式 GetBlogActivity 提供,程式碼大致如下:
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)
{
// 已尝试过 Passport 刷新仍出错,为避免无限循环,就此停止
response = "error";
}
else
{
// 构造响应:用一个 iframe 载入并刷新 Passport 凭证
var timer = setTimeout(DisplayContentLoadError(item, entryid), 10000); // 10 秒内未清除则失败
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 的同步請求方式(open("POST", url, false) 的第三個參數為 false)。這就是為什麼每次點擊「閱讀評論」時,頁面都會稍微停頓一下的原因。
上述程式中的 BlogJSPostUrl 定義在共享空間的首頁,其餘函式則定義在 BlogJS.js 檔裡。更詳細的闡述,可參考《AJax 開發詳解》一書中「模擬 MSN Space」的章節。