首先,在HTML页面创建基本格式,并创建d名为show的div模块
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="show"></div>
</body>
</html>
其次,在HTML页面下使用script获取show方法
show();
//用来显示数据
function show(){
//1.创建ajax对象
var ajax = new XMLHttpRequest();
//2.用来连接服务器
ajax.open('get','show.php','true');
//3.发送请求
ajax.send(null);
/*
ajax:接值:
1.监听事件:onreadystatechang去监听ajax.readyState什么时候等于4
2.判断 :ajax.readyState==4 ajax.status=200
3.接值:ajax.responseText
*/
ajax.onreadystatechange = function(){
if(ajax.readyState==4&&ajax.status==200){
var c = ajax.responseText;
//alert(c);
document.getElementById("show").innerHTML = c;
}
}
}
调用show.php页面,PHP页面方法如下
<?php
header("content-type:text/html;charset=utf-8");
mysql_connect("127.0.0.1","root","root");
mysql_select_db("1604");
mysql_query("set names utf8");
$sql = "SELECT * FROM user";
//echo $sql;
$res = mysql_query($sql);
//取一行
//$data = mysql_fetch_assoc($res)
//取多行
while($data = mysql_fetch_assoc($res)){
$arr[] = $data;
}
//print_r($arr);
?>
<table border='1'>
<tr>
<td>编号</td>
<td>姓名</td>
<td>年龄</td>
<td>性别</td>
<td>爱好</td>
<td>手机号</td>
<td>操作</td>
</tr>
<?php foreach ($arr as $key => $val) { ?>
<tr>
<td><?php echo $val['id'] ?></td>
<td><?php echo $val['name'] ?></td>
<td><?php echo $val['age'] ?></td>
<td><?php echo $val['sex'] ?></td>
<td><?php echo $val['hobby'] ?></td>
<td><?php echo $val['tel'] ?></td>
<td><a href="#" onclick="del(<?php echo $val['id'] ?>)">删除</a></td>
</tr>
<?php } ?>
</table>
调用ajajx删除方法
//删除函数
function del(id){
//1.创建ajax对象
var ajax = new XMLHttpRequest();
//2.用来连接服务器
ajax.open('get','del.php?id='+id,'true');
//3.发送请求
ajax.send(null);
/*
ajax:接值:
1.监听事件:onreadystatechang去监听ajax.readyState什么时候等于4
2.判断 :ajax.readyState==4 ajax.status=200
3.接值:ajax.responseText
*/
ajax.onreadystatechange = function(){
if(ajax.readyState==4&&ajax.status==200){
var c = ajax.responseText;
if(c=='1'){
//删除成功 重新显示一下数据
alert("删除成功");
//重新显示一下数据
show();
}else{
alert("删除失败");
}
}
}
}
传值到del.php页面
<?php
$id = isset($_GET['id'])?$_GET['id']:'';
mysql_connect("127.0.0.1","root","root");
mysql_select_db("1604");
mysql_query("set names utf8");
$sql = "DELETE FROM user WHERE id=$id";
//echo $sql;
$res = mysql_query($sql);
if($res){
//删除成功
echo 1;
}else{
//删除失败
echo 2;
}
?>
异步ajax显示和删除完成