How to convert jQuery.serialize() data to JSON object?

后端 未结 12 2166
感情败类
感情败类 2020-12-02 17:11

Is there any better solution to convert a form data that is already serialized by jQuery function serialize(), when the form contains multiple input Array fields. I want to

12条回答
  •  眼角桃花
    2020-12-02 17:19

    I'm using this very little jQuery plugin, that I've extended from DocumentCloud:

    https://github.com/documentcloud/documentcloud/blob/master/public/javascripts/lib/jquery_extensions.js

    It is basically two lines of code, but it requires _.js (Underscore.js), since it is based on a reduce function.

    $.fn.extend({
      serializeJSON: function(exclude) {
        exclude || (exclude = []);
        return _.reduce(this.serializeArray(), function(hash, pair) {
          pair.value && !(pair.name in exclude) && (hash[pair.name] = pair.value);
          return hash;
        }, {});
      }
    });
    

    Extensions:

    • It doesn't serialize an input value if it's null
    • It can exclude some inputs by passing an array of input names to the exclude argument i.e. ["password_confirm"]

提交回复
热议问题