源码演示如上:
源码:
index.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script>
//创建ajax引擎
function getXmlHttpObject(){
var xmlHttpRequest;
// 不同的浏览器获取对象xmlHttprequest 对象方法不一样
if(window.ActiveXObject){
xmlHttpRequest = new ActiveXObject("Micosoft.XMLHTTP");
}else{
xmlHttpRequest = new XMLHttpRequest();
}
return xmlHttpRequest;
}
var myXmlHttpRequest ="";
// 执行表格添加
function myTable(){
myXmlHttpRequest = getXmlHttpObject();
// 怎么判断是否创建成功
if(myXmlHttpRequest){
// POST
var url="/test/post.php";
var data="username="+$("username").value+"&age="+$("age").value+"&job="+$("job").value;
// 打开请求
myXmlHttpRequest.open("post",url,true);
// POST 还有一句话,这句话必须
myXmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
// 指定回调函数 handle是函数名
myXmlHttpRequest.onreadystatechange=handle;
// 发送请求 如果是get请求则填入 null 即可
// myXmlHttpRequest.send(null);
// 如果是post 请求,则填入实际的数据
// POST
myXmlHttpRequest.send(data);
}
}
// 回调函数
function handle(){
// 判断是否执行成功
if(myXmlHttpRequest.readyState==4){
if(myXmlHttpRequest.status==200){
// 取回成功后的数据
var json=myXmlHttpRequest.responseText;
var tbody=document.createElement("tbody");
tbody.innerHTML=json;
$("my_table").appendChild(tbody);
}
}
}
function $(id){
return document.getElementById(id);
}
</script>
</head>
<body>
<div id="result">Ajax增加表格信息
<form id="my" action="" method="post">
<p><span>姓名:</span> <input type="text" name="username" id="username"/></p>
<p><span>年龄:</span><input type="text" name="age" id="age" /></p>
<p><span>工作:</span><input type="text" name="job" id="job"/></p>
</form>
<button id="send" onclick="myTable()">提交</button>
<br/><br/><br/>
<table class="table" id="my_table" border="1px solid">
<tr>
<th>姓名:</th>
<th>年龄:</th>
<th>工作:</th>
</tr>
<tr>
<th>小明</th>
<th>18</th>
<th>IT</th>
</tr>
</table>
</body>
</html>
处理程序 post.php
<?php
header("Content-type:text/html;charset=utf-8");
$username = $_POST['username'];
$age = $_POST['age'];
$job = $_POST['job'];
echo "<tr>";
echo "<th>".$username."</th>";
echo "<th>".$age."</th>";
echo "<th>".$job."</th>";
echo "</tr>";
?>



