$.ajax 送出序列化表單資料protected void writeJson(String json) {
PrintWriter pw = null;
try {
servletResponse.setContentType("text/plain;charset=UTF-8");
pw = servletResponse.getWriter();
pw.write(json);
pw.flush();
} 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 + ')'); // 轉為 JS 物件
$("#bindShipmmsiDiv table tbody").html("");
if (ships && 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');
}).dblclick(function(){
fillShipMMSIAndName(this);
$("#bindShipmmsiDiv").hide();
});
}
}
});
$.ajax({
url: 'deliveryWarrant/update.do',
data: $('#myform').serialize(), // 關鍵:自動序列化所有 name 屬性的表單欄位
type: "POST",
success: function(data) {
var res = eval('(' + data + ')');
if (res && res.success) {
alert(res.message);
location.href = "/godownWarrant/findToDeliveryWarrant.do?godownWarrant.code=" + $("#myform input[name='godownWarrant.code']").val();
} else {
alert(res.message);
}
}
});
<%@ page contentType="text/html;charset=UTF-8" %>response.setCharacterEncoding("UTF-8") 必須在 getWriter() 之前呼叫現在建議改用 JSON.parse(data) 取代 eval(),安全性更高;若使用 jQuery 3+,可直接設定 dataType: "json" 自動解析。