2012-07-28 45 views
3

jQuery.serializeArray目前返回此結果:格式化serializeArray

[Object { name="id", value="0"}, Object { name="gender[]", value="1"}, Object { name="gender[]", value="2"}, Object { name="countries[]", value="AU"}, Object { name="countries[]", value="GB"}, Object { name="ages[]", value="25"}, Object { name="ages[]", value="99"}] 

我想獲得的結果在這條路上格式化:

{id: 0, gender: ['1', '2'], countries: ['AU', 'GB'], ages: ['25', '99']} 

如何實現這一目標?

我不喜歡serializeArray如何格式化它的輸出,並且我創建了一個以更可接受的方式格式化它的函數。

(function($){ 
$.fn.serializeJSON=function() { 
    var json = {}, propname; 
    $.each($(this).serializeArray(), function(index, n){ 
     propname = n.name.replace('[]', ''); 
     if (!json.hasOwnProperty(propname)) 
     { 
      json[propname] = n.value; 
     } 
     else if(! (json[propname] instanceof Array)) 
     { 
      json[propname] = new Array(json[propname], n.value); 
     } 
     else 
     { 
      json[propname].push(n.value); 
     } 
    }); 
    return json; 
}; 
})(jQuery); 

形式後,將創建只是把某處這段代碼:

$('#form_id').submit(function(e) { 
    e.preventDefault(); 
    e.stopPropagation(); 
    var data = $(this).serializeJSON(); 
    console.log(data); 
}) 

我希望它有助於那些誰喜歡的形式是如何發佈到PHP。

+2

如果不是它不屬於這裏的問題。但是,您可以將問題制定爲**問題**並將您的解決方案提供爲**答案**。 FWIW,因爲函數'serializeJSON'實際上並不返回JSON,所以我會將它重命名爲更合適的。 – 2012-07-28 16:31:55

+0

我會傾向於同意費利克斯的觀點,但同樣的,這個姿勢也是一個深思熟慮的姿勢,所以+1。 OP,如果你可以調整爲問題答案,這將是盛大的。 – halfer 2012-07-28 21:52:36

+0

當前格式化輸出示例以及您的自定義函數如何格式化,將使我們更容易理解問題... – 2012-07-28 22:25:41

回答

0

我用這個:

$.fn.serializeObject = function(options) { 

    options = $.extend({}, options); 

    var self = this, 
     json = {}, 
     push_counters = {}, 
     patterns = { 
      "validate": /^[a-zA-Z][a-zA-Z0-9_]*(?:\[(?:\d*|[a-zA-Z0-9_]+)\])*$/, 
      "key":  /[a-zA-Z0-9_\sąćęłóśżźĄĆĘŁÓŚŻŹ\/-]+|(?=\[\])/g, 
      "push":  /^$/, 
      "fixed": /^\d+$/, 
      "named": /^[a-zA-Z0-9_]+$/ 
     }; 


    this.build = function(base, key, value){ 
     base[key] = value; 
     return base; 
    }; 

    this.push_counter = function(key){ 
     if(push_counters[key] === undefined){ 
      push_counters[key] = 0; 
     } 
     return push_counters[key]++; 
    }; 

    $.each($(this).serializeArray(), function(){ 
     var k, 
      keys = this.name.match(patterns.key), 
      merge = this.value, 
      reverse_key = this.name; 

     while((k = keys.pop()) !== undefined){ 
      reverse_key = reverse_key.replace(new RegExp("\\[" + k + "\\]$"), ''); 

      merge = self.build({}, k, merge); 
     } 
     json = $.extend(true, json, merge); 
    }); 

    return json; 
};