serialize()
원문 링크
http://api.jquery.com/serialize/
개요 : 데이터를 보내기 위해 폼 요소 집합을 문자열로 인코딩 합니다.
- serialize()
.serialize() 함수는 표준 URL-encoded 표기법으로 텍스트 문자열을 만듭니다. 이 함수는 폼 요소 집합을 표현하는 jQuery 객체를 이용합니다. 폼 요소들은 여러가지가 있습니다.
<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>.serialize() 함수는 jQuery 객체로 사용할 수 있는데, 폼 요소 개별 객체별로 사용할 수 있습니다. 즉 <input>, <textarea>, <select>와 같은 개별 요소들이 이 함수를 사용할 수 있는 것입니다. 하지만, 대체적으로 아래 예제와 같이 <form> 태그를 선택해서 직렬화 하는 방식이 많습니다.
$('form').submit(function() {
alert($(this).serialize());
return false;
});위 예제는 표준 형태의 쿼리 스트링을 만들어 내게 됩니다.
a=1&b=2&c=3&d=4&e=5
Warning: 폼과 내부 자식 요소를 동시에 선택하면 직렬화 시 중복 문자열이 발생할 수 있습니다.
Note: 오로지 "successful controls" 들만 문자열로 직렬화가 됩니다. 폼 요소는 반드시 name 속성을 가지고 있어야 직렬화에 포함 됩니다. checkboxes 와 radio button 은 선택된 것만 포함이 됩니다. type='file' 요소는 포함되지 않습니다.
위의 note가 핵심인 것 같습니다. "successful controls"가 무엇인지 링크를 꼭 확인해 보시기 바랍니다. 아~ 영어입니다. 찾아봤더니 한글도 있는데 뭐 한글도 해석해야 하네요. ㅡㅡ;; successful controls 한글
예 제
폼 값을 직렬화하고, Ajax 요청 시 데이터로 보냅니다.
<!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://code.jquery.com/jquery-latest.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>미리보기
많은 데이터를 Ajax로 보낼 때 사용하세요. 그런데 파일 업로드가 안되서 딱히 실용적이지는 않네요.
그럼 즐프하세요.
※ 본 예제는 http://www.jquery.com 에 있는 내용임을 밝힙니다.