用 jQuery 手動序列化表單再送出,遇到 file 上傳或複雜欄位時就會顯得笨拙。jquery.form 插件提供 ajaxSubmit,把整個表單(含檔案)交給它處理,成功後直接進回呼,程式碼乾淨不少。
<script type="text/javascript" src="${ctx}/js/jquery.form.js"></script>
<script type="text/javascript">
// 建立測試實例
function createInstance() {
var options = {
success : function(json) {
if (json.succ) {
alert(json.info);
window.parent.ymPrompt.doHandler("close", true);
}
}
};
$("#f1").ajaxSubmit(options);
}
// 關閉視窗
function closeWindow() {
window.parent.ymPrompt.doHandler("close", true);
}
</script>
<form id="f1" name="f1" action="${ctx}/process/createInstance.do" method="post">
<table style="width:100%; height:100%">
<tr>
<td nowrap="nowrap" style="text-align:right;">測試名稱:</td>
<td><input type="text" name="name" value="${instance.name}"
style="width:265px;" /><em class="em_user_manage">*</em>
</td>
</tr>
<tr>
<td nowrap="nowrap" style="text-align:right;">測試場景:</td>
<td><input type="text" name="scene" style="width:265px;"
value="${instance.scene}" /><em class="em_user_manage">*</em>
</td>
</tr>
<tr>
<td nowrap="nowrap" style="text-align:right;">測試目標:</td>
<td><textarea name="goal" id="goal" cols="32" rows="7">${instance.goal}</textarea>
</td>
</tr>
<tr>
<td nowrap="nowrap" style="text-align:right;">測試說明:</td>
<td><textarea name="description" id="description" cols="32" rows="7">${instance.description}</textarea>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="hidden" name="extProcessDefinitionId" value="${instance.extProcessDefinitionId}" />
<input type="hidden" name="signIn" value="${instance.signIn}" />
<input type="hidden" name="definitionId" value="${instance.definitionId}" />
<input type="button" value="確定" onclick="createInstance();" />
<input type="button" value="取消" onclick="closeWindow();" />
</td>
</tr>
</table>
</form>
按下確定時呼叫 createInstance(),它組出一個 options 物件並交給 $("#f1").ajaxSubmit(options)。插件會自動收集表單中所有具 name 的欄位、依 form 的 action 與 method 送出,成功後把回應交給 success 回呼。這裡預期回傳的是 JSON 物件,因此可以直接讀 json.succ 與 json.info。
三個 hidden 欄位分別帶著流程定義 ID、簽入資訊與定義 ID,是因為這個表單被包在流程引擎的對話框裡,提交時需要把上下文一併送回。
dataType 要明確指定。若不設 dataType: 'json',插件會依伺服器回應的 Content-Type 判斷,回傳的字串就可能不是物件,json.succ 便會出錯。伺服器端也必須正確設定 Content-Type: application/json。
textarea 少了 type 屬性。原範例寫成 <textarea type="text">,textarea 沒有 type 屬性,寫了不會報錯但沒有意義,可以移除。
成功提示不該用 alert。alert 會中斷操作,改用頁面內的訊息區塊或前面提過的 jGrowl 這類非阻塞提示,體驗會好很多。
別忘了 error 回呼。範例只處理了成功路徑,網路失敗或伺服器 500 時使用者得不到任何回饋。至少要加上 error 提示,並在 beforeSubmit 階段做必填驗證,避免送出明顯不完整的資料。
最後,window.parent.ymPrompt.doHandler 是特定 iframe 對話框元件的寫法,換到別的專案要替換成對應的關閉方式;如果這個表單並非嵌在 iframe 中,直接呼叫自己的關閉函式即可。