FormData實現form表單的數據打包
2015-02-04
HTML代碼:
<html> <head> <title>FormData</title> <script type="text/javascript"> /*formData 表單數據 這是在html5中新增的一個API 能以表單對象作為參數,自動的把表單的數據打包 當ajax發送數據時,發送些formData, 達到發送表單內各數據的目的。 */ function send(){ //獲取form的dom對象 var fm = document.getElementById('tform'); //將form數據用formData打包 var fd = new FormData(fm);
var xhr = new XMLHttpRequest(); xhr.open('POST','FormData.php',true); //post發送 xhr.onreadystatechange = function(){ if(this.readyState == 4){ document.getElementById('debug').innerHTML = this.responseText; } } xhr.send(fd); } </script> </head> <body> <form id="tform"> 用戶名:<input type="text" name="username" /><br/> 年齡:<input type="text" name="age" /><br/> 郵件:<input type="text" name="email" /><br/> 性別:<input type="text" name="gender" /><br/> <input type="button" value="Ajax發送" onclick="send();" /><br/> </form> <div id = "debug"></div> </body> </html> |
PHP代碼
<?php
print_r($_POST);
?>
如圖所示,php的POST輸出了,針對輸入的form表單的打包數據
使用 formdata的對象 .append('key','value'),可以實現對數據的增加
同樣:
formdata 不僅可以實現對數據的打包, 還可以人為的添加數據
//建立一個空的formData數據
var fd2 = new FormData();
//人為的添加數據
fd2.append('username',"zhangsan");
fd2.append('age',23);
xhr.send(fd2);
運行后,可以看到,我們並未數據,顯示的數據是我們append得到的