form表單序列化成json數據 去除空值(form表單中checkBox數據會用逗號隔開拼接成字符串)

去除空值this

$.fn.serializeJson = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (this.value) {
            if (o[this.name]) {
                o[this.name] = o[this.name] + ',' + this.value || '';
            } else {
                o[this.name] = this.value || '';
            }
        }
    });
    return JSON.stringify(o);
}

不去除空值orm

$.fn.notEmptyserializeJson = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name]) {
            o[this.name] = o[this.name] + ',' + this.value || '';
        } else {
            o[this.name] = this.value || '';
        }
    });
    
    //radio和checkbox爲空值的時候進行處理
    var $radio = $('input[type=radio],input[type=checkbox]', this);
    
    $.each($radio, function () {
        if (!o.hasOwnProperty(this.name)) {
            o[this.name] = '';
        }
    });
    return JSON.stringify(o);
};

使用案列input

//去除空值
var data = $("#formId").serializeJson();

//不去除空值
var data = $("#formId").notEmptyserializeJson();
相關文章
相關標籤/搜索