Home > Web Front-end > JS Tutorial > Introduction to examples of serialize(), serializeArray() and param() methods in JQuery_jquery

Introduction to examples of serialize(), serializeArray() and param() methods in JQuery_jquery

WBOY
Release: 2016-05-16 16:40:45
Original
1262 people have browsed it

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("<div class='comment'><h6> "+username+" :</h6><p class='para'> "+content+" 
</p></div>"); 
%>
Copy after login

Like other methods in JQuery, the serialize() method also acts on a JQuery object, which can serialize the content of DOM elements into strings for 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); 
});
});
Copy after login

When the "Submit" button is clicked, all form elements belonging to form1 can be submitted to the background. Even if more fields are added to the form, the script can still be used and no other redundant work is required.

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 works on JQuery objects, not only forms can use it, but also elements selected by other selectors can use it, such as the following JQuery code:

$(":checkbox,:radio").serialize();
Copy after login

Serialize the values ​​of check boxes and radio buttons into string form. Only the selected values ​​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输出
Copy after login

The $.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 an ordinary object:

var obj = {a:1,b:2,c:3};
var k = $.param(obj);
alert(k); //输出a=1&b=2&c=3
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template