DIV CSS 佈局教程網

jQuery 如何把陣列轉成字串傳到後端並還原處理
編輯:JQuery特效代碼     

批量刪除是後台常見功能:勾選多筆資料,一次送出。問題是表單欄位天生只能送字串,所以前端得先把 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 這樣的結果,正好符合後端切割的需求。

後端:字串還原為 List

/**
 * 批量刪除私信
 */
@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 字串:JSON.stringify(ids) 送出,後端用 JSON 庫解析,型別與轉義都由函式庫負責。

另外,收到字串後最好先過濾非數字並去重,避免 split 出空字串造成 SQL 語法錯誤;用 List<Long> 搭配 IN 查詢做批次刪除,也比逐筆 delete 有效率得多。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved