將Jquery序列化後的表單值轉換成Json

小朋友有一個表單,他想以Json的方式獲取到表單的內容。小朋友嘗試瞭如下方式。segmentfault

經過$("#form").serialize()能夠獲取到序列化的表單值字符串。數組

a=1&b=2&c=3&d=4&e=5

經過$("#form").serializeArray()輸出以數組形式序列化表單值。this

[ 
  {name: 'firstname', value: 'Hello'}, 
  {name: 'lastname', value: 'World'},
  {name: 'alias'}, // 值爲空
]

通通不知足小朋友想獲得Json的願望。堆棧溢出後,找到了一個這樣的方法spa

$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            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.stringify($("#form").serializeObject()); 就能夠獲得Json內容嚕。code

請輸入圖片描述

相關文章
相關標籤/搜索