JQuery serialize of serialization

  • 2020-05-16 06:14:35
  • OfStack

In jQuery, when we use ajax, we often need to assemble input data and send it to the server in the form of a key-value pair (Key/Value). This can be easily done with JQuery's serialize method, which serializes the form into key-value pairs (key1=value1&key2=value2...). After submission. The use of serialize() in JQuery is described below

1. Definition and usage of serialize() :

The serialize() method serializes the form values to create a standard URL encoded text string that operates on an jQuery object representing a collection of form elements. You can select one or more form elements (such as input or text box) or the form element itself. The serialized value can be used in the URL query string when an AJAX request is generated.

Grammar:


$(selector).serialize()

Detailed instructions

1. The.serialize() method creates a text string encoded in standard URL. Its action object is an jQuery object that represents a collection of form elements.

The.serialize() method can manipulate jQuery objects that have selected individual form elements, such as < input > , < textarea > As well as < select > . However, the choice < form > It is easier to serialize the tag itself

3. Serializes only the "successful control" to a string. If you do not use the button to submit the form, the value of the submit button is not serialized. If you want the value of a form element to be included in a sequence string, the element must use the name attribute.

4. name in form cannot use the keywords in Js and jquery.

For example: length


<form id="form1">
   <input name="length" type="text" value="pipi" />
   <input name="blog" type="text" value="blue submarine" />
</form>
// use :$("#form1").serialize();

The top gets no value.

2. Instances of serialize() in JQuery

1, ajax serialize ()


$.ajax({
    type: "POST",
    dataType: "json",
    url:ajaxCallBack,
    data:$('#myForm').serialize(),// To submit the form ID
    success: function(msg){
        alert(msg);
    }
});

2. serialize() serializes the form instance


 <script src="jquery-1.7.min . js"></script>
<script>
$(function(){
   $("#submit").click(function(){
     alert($("#myForm").serialize());
   });
});
</script>
<form id="myForm">
nickname <input type="text" name="username" value="admin" /><br />
password <input type="password" name="password" value="admin123" /><br />
<input type="button" id="submit" value=" Serialized form " />
</form>

Click the button and it pops up:


username=admin&password=admin123

3. serialize is a simple package of serializeArray using the param method

1, $. param ()

The $.param () method is the core of the serialize() method, used to serialize an array or object by key/value.

The js code for the param method


 param: function( a ) {
        ///    <summary>
        ///        This method is internal.  Use serialize() instead.
        ///    </summary>
        ///    <param name="a" type="Map">A map of key/value pairs to serialize into a string.</param>'
        ///    <returns type="String" />
        ///    <private />
        var s = [ ];
        function add( key, value ){
            s[ s.length ] = encodeURIComponent(key) + '=' + encodeURIComponent(value);
        };
        // If an array was passed in, assume that it is an array
        // of form elements
        if ( jQuery.isArray(a) || a.jquery )
            // Serialize the form elements
            jQuery.each( a, function(){
                add( this.name, this.value );
            });
        // Otherwise, assume that it's an object of key/value pairs
        else
            // Serialize the key/values
            for ( var j in a )
                // If the value is an array then the key names need to be repeated
                if ( jQuery.isArray(a[j]) )
                    jQuery.each( a[j], function(){
                        add( j, this );
                    });
                else
                    add( j, jQuery.isFunction(a[j]) ? a[j]() : a[j] );
        // Return the resulting serialization
        return s.join("&").replace(/%20/g, "+");
    }

For example,


var obj = {a:1,b:2,c:3};
var k = $.param(obj);
alert(k);    // The output a=1&b=2&c=3

2, serializeArray

The serializeArray method serializes the fields in a form into an array

jquery definition of the serializeArray method


serializeArray: function() {
        ///    <summary>
        ///        Serializes all forms and form elements but returns a JSON data structure.
        ///    </summary>
        ///    <returns type="String">A JSON data structure representing the serialized items.</returns>
        return this.map(function(){
            return this.elements ? jQuery.makeArray(this.elements) : this;
        })
        .filter(function(){
            return this.name && !this.disabled &&
                (this.checked || /select|textarea/i.test(this.nodeName) ||
                    /text|hidden|password|search/i.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};
                    }) :
                    {name: elem.name, value: val};
        }).get();
    }

serializeArray data example


[ {   name : username,   value : China    }, {   name : password,   value : xxx  }]

That's all for this article, I hope you enjoy it.


Related articles: