點擊按鈕切換商品上架狀態,需傳遞三個參數:上架狀態、上架時間、上架人,異步更新數據庫並刷新界面。
<button class="toggle-status" data-id="${goods.id}" data-status="${goods.status}">
${goods.status == 1 ? '下架' : '上架'}
</button>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script>
$(document).on('click', '.toggle-status', function() {
var btn = $(this);
var goodsId = btn.data('id');
var newStatus = btn.data('status') == 1 ? 0 : 1;
var operator = '${sessionScope.loginUser.name}'; // 當前登錄用戶
$.ajax({
url: 'goods/toggleStatus',
type: 'POST',
data: {
id: goodsId,
status: newStatus,
operator: operator,
timestamp: new Date().getTime()
},
dataType: 'json',
success: function(resp) {
if (resp.success) {
btn.data('status', newStatus);
btn.text(newStatus == 1 ? '下架' : '上架');
alert('操作成功');
} else {
alert('失敗: ' + resp.msg);
}
},
error: function() { alert('網絡錯誤'); }
});
});
</script>
@WebServlet("/goods/toggleStatus")
public class ToggleGoodsStatusServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
resp.setContentType("application/json;charset=UTF-8");
try {
Long id = Long.parseLong(req.getParameter("id"));
Integer status = Integer.parseInt(req.getParameter("status"));
String operator = req.getParameter("operator");
Long timestamp = Long.parseLong(req.getParameter("timestamp"));
// 業務邏輯:更新數據庫
GoodsService service = new GoodsService();
boolean success = service.updateStatus(id, status, operator, timestamp);
// 返回 JSON
PrintWriter out = resp.getWriter();
out.write("{\"success\":" + success + ",\"msg\":\"" + (success ? "" : "更新失敗") + "\"}");
} catch (Exception e) {
resp.getWriter().write("{\"success\":false,\"msg\":\"參數錯誤: " + e.getMessage() + "\"}");
}
}
}
public class GoodsService {
public boolean updateStatus(Long id, Integer status, String operator, Long timestamp) {
String sql = "UPDATE goods SET status=?, update_time=?, update_by=? WHERE id=?";
try (Connection conn = DataSourceUtils.getConnection();
PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, status);
ps.setTimestamp(2, new Timestamp(timestamp));
ps.setString(3, operator);
ps.setLong(4, id);
return ps.executeUpdate() > 0;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
}
PreparedStatement 防 SQL 注入data-* 屬性存儲狀態,避免全局變量