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

后端 未结 12 2177
感情败类
感情败类 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:20

    I think there're a lot of good answer here, and I made my own function based on these answers.

    function formToJSON(f) {
        var fd = $(f).serializeArray();
        var d = {};
        $(fd).each(function() {
            if (d[this.name] !== undefined){
                if (!Array.isArray(d[this.name])) {
                    d[this.name] = [d[this.name]];
                }
                d[this.name].push(this.value);
            }else{
                d[this.name] = this.value;
            }
        });
        return d;
    }
    
    //The way to use it :
    $('#myForm').submit(function(){
        var datas = formToJSON(this);
        return false;
    });
    

    Well let me explain basically why I prefer this solution... If you have multiples input with the same name, all values will be stored in an Array but if not, the value will be stored directly as the value of the index in the JSON ... This is where it's different from Danilo Colasso's answer where the JSON returned is only based of array values...

    So if you have a Form with a textarea named content and multiples authors, this function will return to you :

    {
        content : 'This is The Content',
        authors : 
            [
                0: 'me',
                1: 'you',
                2: 'him',
            ]
    }
    

提交回复
热议问题