利用 $.fn 可以讓每一個jquery 對象都能直接使用這個方法。
//form表單轉化json對象
$.fn.serializeObject = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$.fn.serializeObjectNoNullAttr = function () {
var data = this.serializeObject();
for (var p in data) {
if (data[p] == null || data[p] == '') {
delete data[p];
}
}
return data;
};
用法:
$("#searchForm").serializeObjectNoNullAttr()