现在的位置: 首页 > 综合 > 正文

jQuery源码分析 :表单序列化动作

2019年10月29日 ⁄ 综合 ⁄ 共 1935字 ⁄ 字号 评论关闭

jQuery源码分析 :表单序列化动作

首先需要明白默认表单提交动作会如何将数据发送到服务器

1)对表单字段的名称和值进行URL编码,使用&分隔

2)不发送禁用的表单字段

3)只发送勾选的复选框和单选按钮

4)不发送type为"reset"和"button"的按钮

5)多选选择框中的每个选中的值单独一个条目

6)在单击提交按钮提交表单的情况下,也会发送提交按钮;否则,不发过提交按钮,也包括type为"image"的<input/>元素

7)<select/>元素的值,就是选中的<option/>元素的value特性的值。如果<option/>元素没有value特性,则是<option/>元素的文本值。

在表单序列化过程中,一般不包含任何按钮字段,因为结果字符串很可能是通过其它方式提交的,如ajax

jQuery表单序列化调用实便 :var data = $('#id').serialize();  // 'name1=value1&name2=value2&....'

jQuery表单序列化源码 :
serialize: function() {
    return jQuery.param( this.serializeArray() );
},

serializeArray: function() {
    return this.map(function(){
        return this.elements ? jQuery.makeArray( this.elements ) : this;
    })
    .filter(function(){
        return this.name && !this.disabled &&
            ( this.checked || rselectTextarea.test( this.nodeName ) ||
                rinput.test( this.type ) );
    })
    .map(function( i, elem ){
        var val = jQuery( this ).val();

        return val == null ?
            null :
            jQuery.isArray( val ) ?
                jQuery.map( val, function( val, i ){
                    return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
                }) :
                { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
    }).get();
}

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

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

    // If an array was passed in, assume that it is an array of form elements.
    if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
        // Serialize the form elements
        jQuery.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 ( var prefix in a ) {
            buildParams( prefix, a[ prefix ], traditional, add );
        }
    }

    // Return the resulting serialization
    return s.join( "&" ).replace( r20, "+" );
}

抱歉!评论已关闭.