1.serialize() 定義和用法: -= serialize() 方法通過序列化表單值,創(chuàng)建 URL 編碼文本字符串。 您可以選擇一個或多個表單元素(比如 input 及/或 文本框),或者 form 元素本身。 序列化的值可在生成 AJAX 請求時用于 URL 查詢字符串中。
語法:
$(selector).serialize()
例如:
var data=$('form').serialize() ;//序列化成URL字符串` var strUrl = decodeURIComponent(data,true)//數(shù)據(jù)解碼
輸出結(jié)果:
apple=蘋果&banana=香蕉&pineapple=菠蘿&orange=橘子
2.serializeArray() 定義和用法: -= serializeArray() 方法通過序列化表單值來創(chuàng)建對象數(shù)組(名稱和值)。 您可以選擇一個或多個表單元素(比如 input 及/或 textarea),或者 form 元素本身。
語法:
$(selector).serializeArray()
例如:
$('form').serializeArray() ;//序列化成json數(shù)組 輸出結(jié)果:
[{"name":"apple","value":"蘋果"},{"name":"banana","value":"香蕉"},{"name":"pineapple","value":"菠蘿"},{"name":"orange","value":"橘子"}]
3.應(yīng)用事例 -= <html> <head> <script type="text/javascript" src="/jquery/jquery.js"> </head> <body> <form> 蘋果:<input type = 'text' name='apple' value = '蘋果'></input><br/> 香蕉:<input type = 'text' name='banana' value = '香蕉'></input><br/> 菠蘿:<input type = 'text' name='pineapple' value = '菠蘿'></input><br/> 橘子:<input type = 'text' name='orange' value = '橘子'></input><br/> </form>
<button>序列化表單值</button>
<div>
序列化成字符串:<span class ='span1' ></span ><br/>
序列化成json數(shù)組:<div class ='span2' ></div ><br/>
轉(zhuǎn)換json數(shù)組數(shù)據(jù):<div class ='span3' ></div ><br/>
</div>
</script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
var data=$('form').serialize() ;//序列化成字符串
var strUrl = decodeURIComponent(data,true)
var arry=$('form').serializeArray() ;//序列化成json數(shù)組
var arry = JSON.stringify(arry);
var json ={};
$.each($('form').serializeArray(),function(index){
json[this['name'] ]=this['value'];
})
$(".span1").text(strUrl );
$(".span2").text(arry);
$(".span3").text(arry);
});
});
</script>
</body>
</html>
結(jié)果:
更多建議: