The
serialize() method also acts on a JQuery object, which can serialize the DOM element content into a string. The serializeArray() method does not return String, but serializes the DOM elements and returns data in JSON format
The following is the jsp code on the server side:
<%@ 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("<p class='comment'><h6> "+username+" :</h6><p class='para'> "+content+" </p></p>"); %>
With other JQuery The same method, the serialize() method also acts on a JQuery object, which can serialize the DOM element content into a string for use in ajax requests. By using the serialize() method, you can submit all fields of this page. The code is as follows:
$("#send").click(function(){ $.get("get1.jsp", $("#form1").serialize(), function(data, textStatus) $("#resText").html(data); }); });
When the "Submit" button is clicked, all form elements belonging to form1 are It can be submitted to the background. Even if more fields are added to the form, the script can still be used and there is no need to do other redundant work.
When using string mode, you need to pay attention to character encoding (Chinese problem). If you don’t want encoding to cause trouble, you can use the serialize() method, which will automatically encode.
Because the serialize() method acts on the JQuery object, not only the form can use it, but also the elements selected by other selectors can use it, such as the following JQuery code:
$(":checkbox,:radio").serialize();
Serialize the values of checkbox and radio button into string form. Only the selected value will be serialized.
There is also a method similar to serialize() in JQuery - serializeArray(). This method does not return a string, but serializes the DOM elements and returns data in JSON format. The JQuery code is as follows:
var fields = $(":checkbox,:radio").serializeArray(); console.log(fields); //用FireBug输出
$.param() method is the core of the serialize() method, which is used to serialize an array or object according to key/value.
For example, serialize a common object:
var obj = {a:1,b:2,c:3}; var k = $.param(obj); alert(k); //输出a=1&b=2&c=3
The above is the detailed content of Introduction to examples of serialize(), serializeArray() and param() methods in JQuery. For more information, please follow other related articles on the PHP Chinese website!