本文提供一個利用 prototype.js 進行 AJAX POST 提交的完整範例,包含前端頁面與後端處理程式。
<%@LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PROTOTYPE POST</title>
<script language="Javascript" type="text/javascript" src="/script/prototype.js"></script>
</head>
<body>
<script type="text/javascript">
function postNewContact() {
var form = $('form');
var url = 'test2.asp';
var myAjax = new Ajax.Request(url, {
method: 'post',
parameters: Form.serialize(form),
onComplete: showResponse
});
}
function showResponse(originalRequest) {
alert(originalRequest.responseText);
}
</script>
<form method="post" id="form" name="form">
<input type="text" name="act">
<input name="pbut" type="button" value="POST" />
</form>
</body>
</html>
<%=request("act")%>
打開 index.html 後,在文字框輸入字元並點擊 POST 按鈕,就能看到提交後正確回傳的結果。這裡的關鍵是透過 prototype.js 提供的 Ajax.Request 物件,搭配 Form.serialize() 把表單資料序列化後送出,大幅簡化了 traditional 的請求撰寫流程。