1. 程式人生 > >jquery 表單序列化

jquery 表單序列化

方法 集合 編碼 cti targe 數組 value src 文本

1.序列化為URL 編碼文本字符串

var serialize = $("form[name=testForm]").serialize();
console.log(serialize);

.serialize() 方法創建以標準 URL 編碼表示的文本字符串。它的操作對象是代表表單元素集合的 jQuery 對象。

結果:

技術分享

2.序列化為JSON對象數組

var serializeArray = $("form[name=testForm]").serializeArray()
console.log(serializeArray);

serializeArray() 方法通過序列化表單值來創建對象數組(名稱和值)。

結果:

技術分享

3.序列化為一個JSON對象

(function($) {
    $.fn.serializeJson = function() {
        var json = {};
        var array = this.serializeArray();
        $.each(array, function() {
            var name = this.name;
            var value = this.value;
            if(value == null || value == "") {
                
return true; } var old = json[name]; if(old) { if($.isArray(old)) { old.push(value); } else { json[name] = [old, value]; } } else { json[name] = value; } });
return json; }; })(jQuery); var serializeJson = $("form[name=testForm]").serializeJson(); console.log(serializeJson);

結果:

技術分享

4.key/value對象序列化為字符串

var param = {};
param.id = 123;
param.age = 20;
console.log(jQuery.param(param));
console.log(jQuery.param(serializeArray));

param() 方法創建數組或對象的序列化表示。

結果:

技術分享

參考地址: http://www.w3school.com.cn/jquery/ajax_param.asp

測試html:

<form name="testForm">
    <input name="id" value="123" />
    <input name="age" value="20" />
</form>

jquery 表單序列化