在做表單聯動時,常有「選擇一條記錄的 ID 後,自動把相關字段填入多個文本框」的需求。本文用 jQuery 的 getJSON 配合後台 Action,示範如何根據 ID 異步取值並填充。
<script type="text/javascript">
function func_load_remark(sr_id){
if(sr_id != 0){
$.getJSON("loadSrRemark.do?date=" + new Date(), {srid: sr_id}, function(srmain){
$("#bparemark").val(srmain.bpa_remark);
$("#itdremark").val(srmain.itd_remark);
$("#bugremark").val(srmain.bu_remark);
$("#itoremark").val(srmain.ito_remark);
});
} else {
$("#bparemark").val("");
$("#itdremark").val("");
$("#bugremark").val("");
$("#itoremark").val("");
}
}
function check(){
if($("#srid").val() == "0"){
alert("請選擇SR_ID!");
$("#srid").focus();
return false;
}
return true;
}
</script>
這裡 URL 後拼接了一個時間戳 new Date(),目的是避免瀏覽器緩存返回結果。回調函數中,把返回的 JSON 對象各字段逐一賦給對應文本框。
public class LoadSrRemarkAction extends BaseAction {
private UserService userService;
public ActionForward executeAction(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
String srid = request.getParameter("srid");
TuOafSrMainTO srMain = userService.getRemarkBySrId(srid);
response.setContentType("application/json;charset=gbk");
response.setCharacterEncoding("gbk");
PrintWriter pw = response.getWriter();
pw.write(JSONUtils.valueToString(JSONSerializer.toJSON(srMain)));
pw.flush();
return null;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
}
後台根據傳入的 srid 查詢數據,把結果對象序列化成 JSON 字符串輸出。這裡使用 json-lib 的 JSONSerializer 完成序列化。特別注意前後台的字符編碼要一致(此例都用 gbk),否則中文容易亂碼。