.serialize()
.serialize() 返回: String
描述: 將用作提交的表單元素的值編譯成字符串。
version added: 1.0.serialize()
.serialize() 方法使用標(biāo)準(zhǔn)的 URL-encoded 符號上建立一個文本字符串. 這是使用jQuery對象代表一組表單元素的構(gòu)成。 這個表單元素可以的幾種類型:
<form>
<div><input type="text" name="a" value="1" id="a" /></div>
<div><input type="text" name="b" value="2" id="b" /></div>
<div><input type="hidden" name="c" value="3" id="c" /></div>
<div>
<textarea name="d" rows="8" cols="40">4</textarea>
</div>
<div><select name="e">
<option value="5" selected="selected">5</option>
<option value="6">6</option>
<option value="7">7</option>
</select></div>
<div>
<input type="checkbox" name="f" value="8" id="f" />
</div>
<div>
<input type="submit" name="g" value="Submit" id="g" />
</div>
</form>
The .serialize() 方法可以操作一個jQuery對象已選定的表單元素個體, 比如 <input>, <textarea>, 和 <select>。無論如何他能非常簡單系列化:選擇的 <form> 標(biāo)簽:
$('form').submit(function() {
alert($(this).serialize());
return false;
});
這個過程產(chǎn)生了一個非常標(biāo)準(zhǔn)的查詢字符串:
a=1&b=2&c=3&d=4&e=5
舉例:
把一個表單序列化成一個查詢字符串,使之能夠在一個Ajax請求中發(fā)送。
<!DOCTYPE html>
<html>
<head>
<style>
body, select { font-size:12px; }
form { margin:5px; }
p { color:red; margin:5px; font-size:14px; }
b { color:blue; }
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<form>
<select name="single">
<option>Single</option>
<option>Single2</option>
</select>
<br />
<select name="multiple" multiple="multiple">
<option selected="selected">Multiple</option>
<option>Multiple2</option>
<option selected="selected">Multiple3</option>
</select>
<br/>
<input type="checkbox" name="check" value="check1" id="ch1"/>
<label for="ch1">check1</label>
<input type="checkbox" name="check" value="check2" checked="checked" id="ch2"/>
<label for="ch2">check2</label>
<br />
<input type="radio" name="radio" value="radio1" checked="checked" id="r1"/>
<label for="r1">radio1</label>
<input type="radio" name="radio" value="radio2" id="r2"/>
<label for="r2">radio2</label>
</form>
<p><tt id="results"></tt></p>
<script>
function showValues() {
var str = $("form").serialize();
$("#results").text(str);
}
$(":checkbox, :radio").click(showValues);
$("select").change(showValues);
showValues();
</script>
</body>
</html>