2013-10-28 52 views
0

我的頁面中有很多表單。我想將它們合併到一個對象中,並將它們提交到一個對象中。但是我發現serializeArray()serialize()與我的請求不匹配,serializeArray函數會生成一個數組對象,並且序列化被get模型使用,它不是一個對象。jquery將表單參數集成到一個對象中

是否有一個jQuery或本地函數可以將它們合併到一個對象中。

我有一個解決方案,但它不是完美的,循環由serializeArray生成的數組對象,使用$.extend將它們合併到一個對象中。有沒有更好的方法?

好心幫忙,謝謝。

+0

我認爲這事情複雜...查看此處http://stackoverflow.com/questions/9280720/serialize-多種形式在一起 – elclanrs

+0

謝謝,但我認爲這不是我想要的。結果將是一個匹配某種格式的字符串。 – Jesse

+0

爲什麼你需要一個對象呢? – elclanrs

回答

0

我自己找到了解決方案,我模仿序列化函數並創建一個簡單的插件。如果有任何缺陷,請大家指出,由於

(function($) { 
$.fn.paramJson = function(a, traditional) { 
    var prefix, s = [], add = function(key, value) { 
     // If value is a function, invoke it and return its value 
     value = $.isFunction(value) ? value() : (value == null ? "" 
       : value); 
     s[s.length] = "\"" + encodeURIComponent(key) + "\"" + ":" + "\"" 
       + encodeURIComponent(value) + "\""; 
    }; 

    // Set traditional to true for jQuery <= 1.3.2 behavior. 
    if (traditional === undefined) { 
     traditional = $.ajaxSettings 
       && $.ajaxSettings.traditional; 
    } 

    // If an array was passed in, assume that it is an array of form 
    // elements. 
    if ($.isArray(a) || (a.jquery && !$.isPlainObject(a))) { 
     // Serialize the form elements 
     $.each(a, function() { 
      add(this.name, this.value); 
     }); 

    } else { 
     // If traditional, encode the "old" way (the way 1.3.2 or older 
     // did it), otherwise encode params recursively. 
     for (prefix in a) { 
      buildParams(prefix, a[prefix], traditional, add); 
     } 
    } 

    // Return the resulting serialization 
    return "{" + s.join(",").replace(r20, "+") + "}"; 
}; 
$.fn.serializeJson = function() { 
    return $.parseJSON($.paramJson(this.serializeArray())); 
};  

})(jQuery的)

相關問題