<form id="addForm">
<input type="text" id="nameInput" placeholder="姓名">
<input type="number" id="ageInput" placeholder="年齡">
<button type="submit">添加</button>
</form>
<script>
document.getElementById("addForm").addEventListener("submit", function(event) {
event.preventDefault(); // 阻止表單的默認(rèn)提交行為
var name = document.getElementById("nameInput").value;
var age = document.getElementById("ageInput").value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(this.responseText);
var table = document.getElementById("dataTable");
var newRow = table.insertRow(-1);
var nameCell = newRow.insertCell(0);
var ageCell = newRow.insertCell(1);
nameCell.innerHTML = response.name;
ageCell.innerHTML = response.age;
}
};
xmlhttp.open("POST", "addData.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("name=" + name + "&age=" + age);
});
</script>