serialize() 方法經過序列化表單值,建立 URL 編碼文本字符串。javascript
您能夠選擇一個或多個表單元素(好比 input 及/或 文本框),或者 form 元素自己。css
序列化的值可在生成 AJAX 請求時用於 URL 查詢字符串中。html
$(selector).serialize()
<html> <head> <script type="text/javascript" src="/jquery/jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ $("div").text($("form").serialize()); }); }); </script> </head> <body> <form action=""> First name: <input type="text" name="FirstName" value="Bill" /><br /> Last name: <input type="text" name="LastName" value="Gates" /><br /> </form> <button>序列化表單值</button> <div></div> </body> </html>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script type="text/javascript" src="js/jquery-1.8.3.min.js"></script> <script type="text/javascript"> $(function(){ $(":submit").click(function(){ alert(1); alert($("form").serialize() ); }); /* $("#username").blur(function(){ var values = $("#username").val(); if(values==""){ alert("用戶名不能爲空,請從新輸入"); } $.ajax({ url :"formServlet?username="+values, //請求的地址 //data :values ,//要發送的數據 type :"get",//請求的方式 dataType : "text" ,//服務器響應的數據類型 json text xml html script success : function(data,status,xhr){ //成功後執行的代碼 //alert(data); if(data=="用戶名可使用"){ $("#username").css("border-color","green"); }else{ $("#username").css("border-color","red"); } }, error : function(error,status,xhr){//失敗後執行的代碼 alert("異步請求出錯"); } }); }); */ }); </script> </head> <body> <form method="POST" name="f1"> <table align="center"> <th>請輸入註冊信息:</th> <tr> <td>用戶名:</td> <td><input type="text" id="username" name="username" /></td><!-- onblur="selectUserName()" --> </tr> <tr> <td>密 碼:</td> <td><input type="password" name="pass" /></td> </tr> <tr> <td>確認密碼:</td> <td><input type="password" name="repass"/></td> </tr> <tr> <td>暱稱:</td> <td><input type="text" name="nickname" /></td> </tr> <tr> <td>真實姓名:</td> <td><input type="text" name="realityname"/></td> </tr> <tr> <td><input type="submit" value="提交" /></td> <td><input type="reset" value="重置"/></td> </tr> </table> </form> </body> </html>