Like other methods in jquery, the Serialize () method acts on a jquery object, which serializes the DOM element content into a string for AJAX requests. By using the Serialize () method, you can submit all the fields of this page,
The code is as follows:
The code is as follows |
Copy Code |
$ ("#form1"). Serialize (); |
When you click the Submit button, all form elements that belong to Form1 can be submitted to the background, and even if you add fields to the form, the script can still be used and no extra work is required.
When you use a string, you need to be aware of the character encoding (Chinese problem), and if you don't want the encoding to be troublesome, you can use the serialize () method, which is automatically encoded.
Because the serialize () method is used for jquery objects, it is not the only form that can be used, but also the elements selected by other selectors, such as the following jquery code:
The code is as follows |
Copy Code |
$ (": Checkbox,:radio"). Serialize (); |
Serializes the value of a check box and a radio box to a string, and only serializes the selected value.
In jquery There is also a method similar to serialize ()--serializearray (), which returns the data in JSON format after serializing the DOM elements instead of returning a string. The jquery code is as follows:
The code is as follows |
Copy Code |
var fields = $ (": Checkbox,:radio"). Serializearray (); Console.log (fields); Output with Firebug
|
The $.param () method is the core of the Serialize () method, which is used to serialize an array or object by Key/value.
such as serialization of a normal object:
The code is as follows |
Copy Code |
var obj = {A:1,b:2,c:3}; var k = $.param (obj); Alert (k); Output a=1&b=2&c=3 |
Look at an example
The following is the server-side JSP code:
code is as follows |
copy code |
<%@ page Language= "java" import= "java.util.*" pageencoding= "UTF-8"%> <% request.setcharacterencoding (" UTF-8 "); String username = request.getparameter ("username"); String content = request.getparameter ("content"); OUT.PRINTLN ("<div class= ' comment ' > </p> </div> "); %> |
Like other methods in jquery, the Serialize () method acts on a jquery object, which serializes the DOM element content into a string for AJAX requests. By using the Serialize () method, you can submit all the fields in this page with the following code:
The code is as follows |
Copy Code |
$ ("#send"). Click (function () { $.get ("get1.jsp", $ ("#form1"). Serialize (), function (data, textstatus) $ ("#resText"). HTML (data); }); }); |
When you click the Submit button, all form elements that belong to Form1 can be submitted to the background, and even if you add fields to the form, the script can still be used and no extra work is required.
When you use a string, you need to be aware of the character encoding (Chinese problem), and if you don't want the encoding to be troublesome, you can use the serialize () method, which is automatically encoded.