標籤:技術分享 type 資料打包 傳統 title cti api 用法 script
FormData 表單資料對象,這是在HTML5中新增的一個API,他能以表單對象做參數,自動的將表單的資料打包,當ajax發送資料是,發送FormData內的表單資料給後端即可
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Document</title></head><script> function fd(){ var fdate = document.getElementById(‘fdate‘); var fd = new FormData(fdate); var xhr = new XMLHttpRequest(); xhr.open(‘post‘,‘10.php‘,true); xhr.send(fd); xhr.onreadystatechange = function(){ if(this.readyState == 4){ document.getElementById(‘desc‘).innerHTML = this.responseText; } } }</script><body> <form id="fdate" > user:<input type="text" name="user"> <br><br> age:<input type="text" name="age"> <br><br> sex:<input type="text" name="sex"> <br><br> QQ:<input type="text" name="QQ"> <br><br> <input type="button" value="Go" onclick="fd();"> </form> <p id="desc"></p></body></html>
效果如下所示:
這樣比傳統的拼接方法簡單多了,當然他還有另外一種用法,如下所示:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Document</title></head><script> function fd(){ var fdate = document.getElementById(‘fdate‘); var fd = new FormData(fdate); var fd2 = new FormData(); var xhr = new XMLHttpRequest(); xhr.open(‘post‘,‘10.php‘,true); //xhr.send(fd); fd2.append(‘user‘,‘leigood‘); fd2.append(‘age‘,‘18‘); xhr.send(fd2); xhr.onreadystatechange = function(){ if(this.readyState == 4){ document.getElementById(‘desc‘).innerHTML = this.responseText; } } }</script><body> <form id="fdate" > user:<input type="text" name="user"> <br><br> age:<input type="text" name="age"> <br><br> sex:<input type="text" name="sex"> <br><br> QQ:<input type="text" name="QQ"> <br><br> <input type="button" value="Go" onclick="fd();"> </form> <p id="desc"></p></body></html>
效果如下所示:
AJAX-----13HTML5中新增的API---FormData