在构建 JSON 对象时跳过表单字段值

skipping form fields values while building json object

本文关键字:表单 字段 构建 JSON 对象      更新时间:2023-09-26

我正在向Javascript发送表单值以使用以下方法构建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;
};

此函数正在构建一个 JSON 对象,但它也为空值构建 JSON。

我希望如果表单字段值为空,它应该总体上跳过它。

让我指导它将如何工作。

希望这会有所帮助!

$.fn.serializeObject = function() {
  var o = {};
  this.filter(function(){
    if(this.value != "")
        o[this.name] = this.value;
  }); 
 return JSON.stringify(o);
};

您还可以在 jsfiddle http://jsfiddle.net/ryuegjuL 中查看结果。让我知道任何进一步的帮助。