js進階 14-8 表單序列化函數serializeArray()和serialize()的區別是什么
一、總結
一句話總結:兩者都是對表單進行序列化,serializeArray()返回的是json對象,serialize()返回的是json形式的字符串,使用起來都是一樣的
?
1、$(selector).serialize()序列化的話對中文做了什么操作?
為了避免出錯,將中文變成了編碼,因為內容要提交到服務器,編碼可以保證漢字不出錯,github上傳文件的時候,也是進行的同樣的操作
?
2、如何正常顯示$(selector).serialize()序列化函數將中文變成的編碼?
decodeURIComponent函數
36 //decodeURIComponent() 函數可對 encodeURIComponent() 函數編碼的 URI 進行解碼。
37 $('#txt').html(decodeURIComponent($('form').serialize()))
?
3、js如何向控制臺輸入消息?
console對象的log方法
56 console.log(obj) //onsole.log() 向web控制臺輸出一條消息
?
?
?
二、表單序列化函數serializeArray()和serialize()的區別是什么
1、相關知識
表單序列化
- 語法:$(selector).serialize()
jQuery的serialize()方法通過序列化表單值,創建URL編碼文本字符串,這樣,我們就可以把序列化的值傳給ajax()作為url的參數,輕松使用ajax()提交form表單了,而不需要一個一個獲取表單中的值然后傳給ajax()
- serializeArray()序列化表單元素(類似'.serialize()'方法返回JSON數據結構數據。
’’’注意’’’此方法返回的是JSON對象而非JSON字符串。
?
2、代碼
1 <!DOCTYPE html> 2 <html lang="en"> 3 <style> 4 </style> 5 <head> 6 <meta charset="UTF-8"> 7 <title>演示文檔</title> 8 <script type="text/javascript" src="jquery-3.1.1.min.js"></script> 9 <style type="text/css"> 10 </style> 11 </style> 12 </head> 13 <body> 14 <form id="form1"> 15 姓名:<input type="text" name="user"><br> 16 電話:<input type="text" name="Tel"><br> 17 <select name="buy"> 18 <option>買新房</option> 19 <option>看二手房</option> 20 </select> 21 <input type="button" value="提交"> 22 </form> 23 <div id="txt"></div> 24 <script> 25 /* 26 $(function(){ 27 $('form input[type=button]').click(function(){ 28 $.ajax({ 29 type:'POST', 30 url:'buy.php', 31 data:$('form').serialize(), 32 success:function(responseTxt,statusTxt,xhr){ 33 //$('#txt').html($('form').serialize()) 34 //alert($('form').serialize()) 35 //字符串形式的鍵值對,并且對URL進行了編碼 36 //decodeURIComponent() 函數可對 encodeURIComponent() 函數編碼的 URI 進行解碼。 37 $('#txt').html(decodeURIComponent($('form').serialize())) 38 39 } 40 }) 41 42 }) 43 }) 44 */ 45 $(function(){ 46 $('form input[type=button]').click(function(){ 47 $.ajax({ 48 type:'POST', 49 url:'buy.php', 50 data:$('form').serializeArray(), 51 success:function(responseTxt,statusTxt,xhr){ 52 //$('#txt').html(responseTxt) 53 var obj=$('form').serializeArray() 54 //alert(obj) 55 //$('#txt').html(obj) 56 console.log(obj) //onsole.log() 向web控制臺輸出一條消息 57 //[{name='user',value=''},{name='user',value=''},{name='user',value=''}] 58 alert(obj[0].name+"=="+obj[0].value) 59 } 60 }) 61 62 }) 63 }) 64 </script> 65 </body> 66 </html>
?
?
?