市面 AJAX 框架林立,反而掩蓋了核心簡單性。本文提供**最小可用實作**,滿足 80%+ 業務場景,專業級複雜頁面再引入成熟庫。
語言不限(Java/PHP/ASP/Node...),甚至靜態檔案皆可。關鍵:Content-Type + charset 正確,內容符合 XML/HTML 規範。
// WebWork Action 範例
public String hotWeek() throws Exception {
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/xml; charset=gb2312");
PrintWriter out = response.getWriter();
StringBuffer html = new StringBuffer();
html.append("<table><tr><td>熱門數據</td></tr></table>");
out.print(html.toString());
return null; // 直接輸出,不走視圖解析
}
var xmlHttp;
function createXMLHttpRequest() {
if (window.ActiveXObject) xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
else if (window.XMLHttpRequest) xmlHttp = new XMLHttpRequest();
}
function startAJaxRequest(method, async, actionUrl, data, invokeMethod) {
createXMLHttpRequest();
xmlHttp.open(method, actionUrl, async);
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.send(data);
function handleStateChange() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
var nodeId = xmlHttp.responseText;
// 統一錯誤碼約定
if (nodeId == "noPermission") { alert("無權限"); }
else if (nodeId.indexOf("false||") != -1) { alert("失敗:" + nodeId.substring(7)); }
else if (nodeId == "false") { alert("失敗,聯繫管理員"); }
else {
if (invokeMethod == undefined) getResult(nodeId);
else invokeMethod(nodeId);
}
}
}
}
}
參數說明:method (GET/POST)、async (通常 true)、actionUrl、data (查詢字串)、invokeMethod (回調函數,可選)
// jQuery 範例
$(document).ready(function() {
var actionUrl = "./provider!hotWeek.action";
$("body").html("頁面載入中...");
startAJaxRequest("GET", true, actionUrl, null);
});
// 預設回調
function getResult(nodeId) {
$("body").html(nodeId); // 直接注入 HTML 片段
}
後端介面網址可換成 myTable.asp、myTable.php 等,只要回傳合法 HTML/XML 片段即可。
**一個 startAJaxRequest 走天下**。核心流程:
XMLHttpRequest(跨瀏覽器)onreadystatechange別讓框架綁架思維。**AJAX = 局部更新協議**,理解本質,輕量實作,按需引入重武器。