批量刪除是後台常見功能:勾選多筆資料,一次送出。問題是表單欄位天生只能送字串,所以前端得先把 ID 陣列序列化,後端再反序列化回集合。
define(function(require, exports, module) {
var Notify = require('common/bootstrap-notify');
module.exports = function($element) {
$element.on('click', '[data-role=batch-delete]', function() {
var $btn = $(this);
var name = $btn.data('name');
// 收集所有被勾選的項目值
var ids = [];
$element.find('[data-role=batch-item]:checked').each(function(){
ids.push(this.value);
});
if (ids.length == 0) {
Notify.danger('未選中任何' + name);
return;
}
if (!confirm('真的要刪除選中的' + ids.length + '條' + name + '嗎?')) {
return;
}
$element.find('.btn').addClass('disabled');
Notify.info('正在刪除' + name + ',請稍等。', 60);
// 陣列轉字串:1,2,3
var values = ids.toString();
$.post($btn.data('url'), { ids: values }, function(){
window.location.reload();
});
});
};
});
這裡的關鍵是 ids.toString()。JavaScript 陣列的 toString() 等同 join(','),會產生 1,2,3 這樣的結果,正好符合後端切割的需求。
/**
* 批量刪除私信
*/
@RequestMapping(value = "/delete", method = {RequestMethod.GET, RequestMethod.POST})
public ResponseEntity<AjaxPostResponse> delete(HttpServletRequest request) {
// 取出待刪除的 ID 字串
String messageIds = ServletRequestUtils.getStringParameter(request, "ids", "");
String[] messageList = messageIds.split(",");
List<String> messageIdList = Arrays.asList(messageList);
logger.info("ids = " + messageIds);
try {
boolean opStatus = messageManager.delete(messageIdList);
logger.info("刪除私信:opStatus={}", opStatus);
return this.okResponse(opStatus);
} catch (Exception e) {
logger.error("刪除私信時發生異常, Cause: ", e);
return this.errorResponse(e.getMessage());
}
}
逗號分隔字串雖然簡單,卻有兩個弱點:值裡若含逗號就會出錯,而且所有型別都得靠字串硬扛。若你的框架支援,改用以下方式會更穩健:
{ ids: ids }(傳陣列),jQuery 會序列化成 ids[]=1&ids[]=2,Spring 可用 @RequestParam List<Long> ids 直接接收。JSON.stringify(ids) 送出,後端用 JSON 庫解析,型別與轉義都由函式庫負責。另外,收到字串後最好先過濾非數字並去重,避免 split 出空字串造成 SQL 語法錯誤;用 List<Long> 搭配 IN 查詢做批次刪除,也比逐筆 delete 有效率得多。