ajax交互案例

时间:2023-03-09 05:48:33
ajax交互案例

数据交互是前端很重要的一部分,静态页是基础,而交互才是网页的精髓。交互又分为人机交互和前后端数据交互,现阶段的互联网下,大部分的网站都要进行前后端数据交互,如何交互呢?交互的流程大概就是前端发送数据给后端,后端接送数据,进行处理,将处理后的结果发送给前端,前端接受数据。前端和后端的收和发通过什么呢?

前端通过表单和ajax发送数据,接受只能通过ajax;后端(php)通过$_GET[]、$_POST[]、$_REQUEST[]接收,打印语句来发送:echo、print、print_r()、die()

ajax是前后端交互的重要手段,ajax的全称是asynchronous JavaScript and XML(异步JavaScript和XML);

这么说可能也感受不出什么,案例来感受下吧!

首先我们要准备下页面布局,布局用到了bootstrap的模态框,可以自己百度看下哈!

 <!DOCTYPE html>
<html lang="en"> <head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="libs/bootstrap.css">
<title>Document</title>
</head> <body>
<div class="container">
<div class="row align-items-center">
<div class="col-2 h1">LOGO</div>
<div class="col-2 h4">学生信息系统</div>
<button type="button" class="btn btn-primary col-1" data-toggle="modal" data-target="#exampleModal"
data-whatever="@mdo" id="insert">添加信息</button>
</div>
<div class="row my-5">
<table class="table table-bordered thead-default table-sm">
<thead>
<tr>
<th>ID</th>
<th>name</th>
<th>machine</th>
<th>examination</th>
<th>delete</th>
<th>update</th>
</tr>
</thead>
<tbody>
<!-- <tr>
<td>1</td>
<td>admin</td>
<td>23</td>
<td>87</td>
<td><span class="btn btn-primary btn-info" ly="delete">删除</span></td>
<td><button type="button" class="btn btn-primary btn-info" data-toggle="modal"
data-target="#exampleModal" data-whatever="@fat" ly="update">修改</button></td>
</tr> -->
</tbody>
</table>
</div>
<div class="row">
<nav aria-label="Page navigation example" class="w-100">
<ul class="pagination pagination-sm justify-content-center">
<li class="page-item disabled"><a class="page-link" href="#">上一页</a></li>
<li class="page-item"><a class="page-link" href="#">1</a></li>
<li class="page-item"><a class="page-link" href="#">2</a></li>
<li class="page-item"><a class="page-link" href="#">3</a></li>
<li class="page-item"><a class="page-link" href="#">下一页</a></li>
</ul>
</nav>
</div>
</div>
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="exampleModalLabel">请输入信息:</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
aria-hidden="true">&times;</span></button>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="recipient-name" class="control-label">姓名:</label>
<input type="text" class="form-control" id="name">
</div>
<div class="form-group">
<label for="message-text" class="control-label">机试:</label>
<input class="form-control" id="cpt" />
</div>
<div class="form-group">
<label for="message-text" class="control-label">笔试:</label>
<input class="form-control" id="pen" />
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary mx-auto" data-dismiss="modal" id="send">提交</button>
</div>
</div>
</div>
</div>
</body>
<script src="libs/jquery-2.2.4.js"></script>
<script src="libs/popper.js"></script>
<script src="libs/bootstrap.js"></script>
<script src="js/ajax.js"></script>
<script src="js/index.js"></script>
</html>

接下来就是js了,其实交互就是增删改查。先来看下查。

; (function () {
2 class Project {
3 constructor() {
4 // 获取元素
5 this.tbody=document.querySelector("tbody");
6 this.addBtn=document.querySelector("#insert");
7 this.submit=document.querySelector("#send");
8 this.name = document.getElementById("name");
9 this.cpt = document.getElementById("cpt");
10 this.pen = document.getElementById("pen");
11 // console.log(this.addBtn);
12 this.selectUrl = "http://localhost/test/project/php/select.php";
16 this.select();
17   }
18 select() {
19 var that = this;
20 ajax({
21 url: this.selectUrl,
22 success: function (res) {
23 // console.log(res);
24 that.res = JSON.parse(res);
25 if (that.res.code) {
26 alert(that.res.msg);
27 } else {
28 // console.log(that.res);
29 that.display();
30 }
31 }
32 });
33 }
34 display() {
35 // console.log(this.res.length);
36 var str = "";
37 for (var i = 0; i < this.res.length; i++) {
38 str += `<tr>
39 <td>${this.res[i].Id}</td>
40 <td>${this.res[i].name}</td>
41 <td>${this.res[i].machine}</td>
42 <td>${this.res[i].examination}</td>
43 <td><span class="btn btn-primary btn-info" ly="delete">删除</span></td>
44 <td><button type="button" class="btn btn-primary btn-info" data-toggle="modal"
45 data-target="#exampleModal" data-whatever="@fat" ly="update">修改</button></td>
46 </tr> `
47 }
48 this.tbody.innerHTML=str;
49 }
50 }
51 new Project();
52 })();

上面的是js部分的代码,封装了ajax所以我直接调用了。再看下php的部分吧!

 <?php
$link=@new mysqli("localhost:3306","root","root","test");
if($link->connect_error){
$err = array("code"=>1,"msg"=>$link->connect_error);
die(json_encode($err));
}
$select="SELECT * FROM stu";
$res=$link->query($select);
if($res){
$str="";
while ($arr=$res->fetch_assoc()) {
$str=$str.json_encode($arr).",";
}
die ("[".substr($str,0,-1)."]");
}else{
$err = array("code"=>2,"msg"=>"失败");
die(json_encode($err));
}
?>

刷新页面的时候就会自动获取数据库中的数据渲染到页面上。再是添加和修改数据,因为使用了一个模态框,所以同时写,因为模态框中的提交按钮需判断是添加按钮触发的还是修改按钮触发的,就需要一个标识。同上,代码感受!

 ; (function () {
class Project {
constructor() {
// 获取元素
this.tbody=document.querySelector("tbody");
this.addBtn=document.querySelector("#insert");
this.submit=document.querySelector("#send");
this.name = document.getElementById("name");
this.cpt = document.getElementById("cpt");
this.pen = document.getElementById("pen");
// console.log(this.addBtn);
this.selectUrl = "http://localhost/test/project/php/select.php";
this.insertUrl="http://localhost/test/project/php/insert.php";
this.updateUrl="http://localhost/test/project/php/update.php"; this.type=0;
this.select();
this.addEvent();
}
select() {
var that = this;
ajax({
url: this.selectUrl,
success: function (res) {
// console.log(res);
that.res = JSON.parse(res);
if (that.res.code) {
alert(that.res.msg);
} else {
// console.log(that.res);
that.display();
}
}
});
}
addEvent(){
var that=this;
this.addBtn.addEventListener("click",function(){
that.type=0;
});
this.tbody.addEventListener("click",function(eve){
var e = eve || window.event;
that.target = e.target || e.srcElement;
if(that.target.getAttribute("y") === "update"){
that.type = 1;
that.id=that.target.parentNode.parentNode.children[0].innerHTML;
that.name.value=that.target.parentNode.parentNode.children[1].innerHTML;
that.cpt.value=that.target.parentNode.parentNode.children[2].innerHTML;
that.pen.value=that.target.parentNode.parentNode.children[3].innerHTML;
}
});
this.submit.addEventListener("click",function(){
that.n=that.name.value;
that.c=that.cpt.value;
that.p=that.pen.value;
if(that.type==0){
that.name.value=that.cpt.value=that.pen.value="";
that.insertLoad();
}else{
// console.log();
that.updateLoad();
}
})
}
insertLoad(){
var that=this;
ajax({
url:this.insertUrl,
data:{
name:this.n,
cpt:this.c,
pen:this.p
},
success:function(res){
// console.log(res);
that.res=JSON.parse(res);
if(that.res.code){
alert(that.res.msg);
}else{
that.display();
}
}
});
}
updateLoad(){
var that=this;
ajax({
url:this.updateUrl,
data:{
id:this.id,
name:this.n,
cpt:this.c,
pen:this.p
},
success:function (res) {
that.res=JSON.parse(res);
if(that.res.code){
alert(that.res.msg);
}else{
that.display();
}
}
})
}
display() {
// console.log(this.res.length);
var str = "";
for (var i = 0; i < this.res.length; i++) {
str += `<tr>
<td>${this.res[i].Id}</td>
<td>${this.res[i].name}</td>
<td>${this.res[i].machine}</td>
<td>${this.res[i].examination}</td>
<td><span class="btn btn-primary btn-info" ly="delete">删除</span></td>
<td><button type="button" class="btn btn-primary btn-info" data-toggle="modal"
data-target="#exampleModal" data-whatever="@fat" ly="update">修改</button></td>
</tr> `
}
this.tbody.innerHTML=str;
}
}
new Project();
})();

下面是添加按钮所对应的的php代码!

 <?php
$link=@new mysqli("localhost:3306","root","root","test");
if($link->connect_error){
$err = array("code"=>1,"msg"=>$link->connect_error);
die(json_encode($err));
}
$n=@$_REQUEST["name"];
$c=@$_REQUEST["cpt"];
$p=@$_REQUEST["pen"];
$insert="INSERT stu (name,machine,examination) VALUES('".$n."',".$c.",".$p.")";
$q=$link->query($insert);
if($q){
echo select();
}else{
$err = array("code"=>3,"msg"=>"添加失败");
die(json_encode($err));
}
function select(){
global $link;
$select="SELECT * FROM stu";
$res=$link->query($select);
if($res){
$str="";
while ($arr=$res->fetch_assoc()) {
$str=$str.json_encode($arr).",";
}
die ("[".substr($str,0,-1)."]");
}else{
$err = array("code"=>2,"msg"=>"失败");
die(json_encode($err));
}
}
?>

下面是修改按钮所对应的的php代码!

 <?php
$link=@new mysqli("localhost:3306","root","root","test");
if($link->connect_error){
$err = array("code"=>1,"msg"=>$link->connect_error);
die(json_encode($err));
}
$id=@$_REQUEST["id"];
$n=@$_REQUEST["name"];
$c=@$_REQUEST["cpt"];
$p=@$_REQUEST["pen"];
$update="UPDATE stu SET name='".$n."',machine=".$c.",examination=".$p." WHERE Id=".$id;
$q=$link->query($update);
if($q){
echo select();
}else{
$err = array("code"=>3,"msg"=>"添加失败");
die(json_encode($err));
}
function select(){
global $link;
$select="SELECT * FROM stu";
$res=$link->query($select);
if($res){
$str="";
while ($arr=$res->fetch_assoc()) {
$str=$str.json_encode($arr).",";
}
die ("[".substr($str,0,-1)."]");
}else{
$err = array("code"=>2,"msg"=>"失败");
die(json_encode($err));
}
}
?>

添加,修改操作完成就是删除,删除是比较简单的,只要获取点击删除的所对应的的数据即可!

 ; (function () {
class Project {
constructor() {
// 获取元素
this.tbody=document.querySelector("tbody");
this.addBtn=document.querySelector("#insert");
this.submit=document.querySelector("#send");
this.name = document.getElementById("name");
this.cpt = document.getElementById("cpt");
this.pen = document.getElementById("pen");
// console.log(this.addBtn);
this.selectUrl = "http://localhost/test/project/php/select.php";
this.insertUrl="http://localhost/test/project/php/insert.php";
this.updateUrl="http://localhost/test/project/php/update.php";
this.deleteUrl="http://localhost/test/project/php/delect.php"; this.type=0;
this.select();
this.addEvent();
}
select() {
var that = this;
ajax({
url: this.selectUrl,
success: function (res) {
// console.log(res);
that.res = JSON.parse(res);
if (that.res.code) {
alert(that.res.msg);
} else {
// console.log(that.res);
that.display();
}
}
});
}
addEvent(){
var that=this;
this.addBtn.addEventListener("click",function(){
that.type=0;
});
this.tbody.addEventListener("click",function(eve){
var e = eve || window.event;
that.target = e.target || e.srcElement;
if(that.target.getAttribute("ly") === "update"){
that.type = 1;
that.id=that.target.parentNode.parentNode.children[0].innerHTML;
that.name.value=that.target.parentNode.parentNode.children[1].innerHTML;
that.cpt.value=that.target.parentNode.parentNode.children[2].innerHTML;
that.pen.value=that.target.parentNode.parentNode.children[3].innerHTML;
}else if(that.target.getAttribute("ly") === "delete"){
that.i=that.target.parentNode.parentNode.children[0].innerHTML;
that.na=that.target.parentNode.parentNode.children[1].innerHTML;
that.ma=that.target.parentNode.parentNode.children[2].innerHTML;
that.ex=that.target.parentNode.parentNode.children[3].innerHTML; that.deleteLoad();
}
});
this.submit.addEventListener("click",function(){
that.n=that.name.value;
that.c=that.cpt.value;
that.p=that.pen.value;
if(that.type==0){
that.name.value=that.cpt.value=that.pen.value="";
that.insertLoad();
}else{
// console.log();
that.updateLoad();
}
})
}
deleteLoad(){
var that=this;
ajax({
url:this.deleteUrl,
data:{
id:this.i,
name:this.na,
cpt:this.ma,
pen:this.ex,
},
success:function(res){
that.res=JSON.parse(res);
if(that.res.code){
alert(that.res.msg);
}else{
that.display();
}
}
})
}
display() {
// console.log(this.res.length);
var str = "";
for (var i = 0; i < this.res.length; i++) {
str += `<tr>
<td>${this.res[i].Id}</td>
<td>${this.res[i].name}</td>
<td>${this.res[i].machine}</td>
<td>${this.res[i].examination}</td>
<td><span class="btn btn-primary btn-info" ly="delete">删除</span></td>
<td><button type="button" class="btn btn-primary btn-info" data-toggle="modal"
data-target="#exampleModal" data-whatever="@fat" ly="update">修改</button></td>
</tr> `
}
this.tbody.innerHTML=str;
}
}
new Project();
})();

删除的php代码!

 <?php
$link=@new mysqli("localhost:3306","root","root","test");
if($link->connect_error){
$err = array("code"=>1,"msg"=>$link->connect_error);
die(json_encode($err));
}
$id=@$_REQUEST["id"];
$n=@$_REQUEST["name"];
$c=@$_REQUEST["cpt"];
$p=@$_REQUEST["pen"];
$delete="DELETE FROM stu WHERE Id=".$id;
$q=$link->query($delete);
if($q){
echo select();
}else{
$err = array("code"=>3,"msg"=>"添加失败");
die(json_encode($err));
}
function select(){
global $link;
$select="SELECT * FROM stu";
$res=$link->query($select);
if($res){
$str="";
while ($arr=$res->fetch_assoc()) {
$str=$str.json_encode($arr).",";
}
die ("[".substr($str,0,-1)."]");
}else{
$err = array("code"=>2,"msg"=>"失败");
die(json_encode($err));
}
}
?>

以上就是交互案例的所有代码了,可以看看,感受下是怎么一回事吧!其实只要理清之间的关系即可,我们做的只是将数据发送给后端并接受后端返回的数据即可!