整條流程可以拆成四段:後端輸出 JSON 字串、前端把它轉成物件、用 serialize() 打包表單、最後處理編碼問題。以下依序說明。
/** 將一個字串輸出到瀏覽器 */
protected void writeJson(String json) {
PrintWriter pw = null;
try {
servletResponse.setContentType("text/plain;charset=UTF-8");
pw = servletResponse.getWriter();
pw.write(json);
pw.flush();
pw.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (pw != null) {
pw.close();
}
}
}
$.ajax({
data: {
"shipmmsi": shipmmsi,
"shipname": shipname
},
url : "shipbk/findShipMMSIAndName.do",
async : true,
type : "POST",
success : function(data) {
var ships = eval('(' + data + ')');
$("#bindShipmmsiDiv table tbody").html("");
if (ships != null) {
if (ships.length) {
$("#bindShipmmsiDiv").show();
var trs = "";
for (var i = 0; i < ships.length; i++) {
trs += "<tr><td>" + ships[i].mmsi + "</td><td>"
+ ships[i].vesselName + "</td></tr>";
}
$("#bindShipmmsiDiv table tbody").append(trs);
// 為每一列註冊點擊事件
$("#bindShipmmsiDiv table tbody tr").click(function(){
$(this).addClass('select_tr').siblings().removeClass('select_tr');
});
$("#bindShipmmsiDiv table tbody tr").dblclick(function(){
fillShipMMSIAndName(this);
$("#bindShipmmsiDiv").hide();
});
}
}
}
});
$.ajax({
url : 'deliveryWarrant/update.do',
data : $('#myform').serialize(),
type : "POST",
success : function(data) {
var res = eval('(' + data + ')');
if (res && res.success == true) {
alert(res.message);
location.href = "/godownWarrant/findToDeliveryWarrant.do?godownWarrant.code="
+ $("#myform input[name=godownWarrant\\.code]").val();
} else {
alert(res.message);
}
}
});
編碼要在每一層都對齊:JSP 頁面用 UTF-8、servlet 用 UTF-8、filter 也用 UTF-8。關鍵的一行是:
response.setCharacterEncoding("UTF-8");
它必須寫在 response.getWriter() 之前,一旦取得 Writer 之後再設定就不生效了。
示範用的 eval('(' + data + ')') 有安全疑慮,且無法防禦格式錯誤的回應。建議改用 dataType: "json" 讓 jQuery 自動解析,或在 callback 中改用 JSON.parse()。
另外,字串拼接組出表格 HTML 的方式,遇到資料中含有角括號或引號時會破壞結構。改用 $("<tr>").text(value) 逐格建立節點,能同時解決轉義與 XSS 問題。
總結來說,畫面前端、Java 程式、資料庫以及資料庫連線都採用同一套編碼,才不會在任一環節冒出亂碼。