var form = document.getElementById("form1");
var formData = new FormData(form);
xhr.send(formData);
formData.append('add_data', '測試'); //在傳送之前新增附加資料
append() 方法包含兩個引數:第 1 個參數列示追加資料的鍵名,第 2 個參數列示追加資料的鍵值。<script> function sendForm(){ var form = document.getElementById("form1"); var formData = new FormData(form); formData.append('grade','3') var xhr = new XMLHttpRequest(); xhr.open('POST','test.php',true); xhr.onload = function(e){ if(this.status == 200){ document.getElementById("result").innerHTML = this.response; } }; xhr.send(formData); } </script> <form id="form1"> 使用者名稱:<input type="text" name="name" /><br /> 密碼:<input type="password" name="pass" /><br /> <input type="button" value="傳送" onclick="sendForm()" /> </form> <output id="result"></output>
<?php $name = $_POST['name']; $pass = $_POST['pass']; $grade = $_POST['grade']; echo '伺服器端接收資料:<br />'; echo '使用者名稱:'.$name.'<br />'; echo '密碼:'.$pass.'<br />'; echo '等級:'.$grade.'<br />'; flush(); ?>演示效果如下: