Examples of serialize of serializeArray of and param of methods in JQuery

  • 2020-03-30 03:40:12
  • OfStack

The following is the server-side JSP 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'><h6> "+username+" :</h6><p class='para'> "+content+" 
</p></div>"); 
%>

Like the other methods in JQuery, the serialize() method ACTS on a JQuery object and serializes the DOM element content as a string for ajax requests. By using the serialize() method, you can submit all fields on this page as follows:


$("#send").click(function(){ 
$.get("get1.jsp", $("#form1").serialize(), function(data, textStatus) 
$("#resText").html(data); 
});
});

When the submit button is clicked, all the form elements that are part of form1 can be submitted to the background, and even if fields are added to the form, the script can still be used without any additional work.

Because the serialize() method works on JQuery objects, it can be used not only by forms, but also by elements selected by other selectors, such as the following JQuery code:


$(":checkbox,:radio").serialize();

Serialize the values of checkboxes and checkboxes as strings. Only the selected values are serialized.

There is also a method in JQuery that is similar to serialize(), serializeArray(), which instead of returning a string, serializes a DOM element and returns data in JSON format. The JQuery code is as follows:


var fields = $(":checkbox,:radio").serializeArray();
console.log(fields); // with FireBug The output 

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

Like serializing a normal object:


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

Related articles: