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

前端通过表单和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));
}
}
?>

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

ajax交互案例的更多相关文章

  1. ThinkPHP中使用ajaxReturn进行ajax交互

    以管理员登录为例来介绍下$this->ajaxReturn与模板页进行ajax交互使用方法 首先看PHP控制器的处理,在application/Admin/Controller/LoginCon ...

  2. struts2 的验证框架validation如何返回json数据 以方便ajax交互

    struts2 的验证框架validation简单,好用,但是input只能输出到jsp页面通过struts2的标签<s:fielderror  />才能取出,(EL应该也可以). 如果使 ...

  3. struts2中使用json插件实现ajax交互

    json插件可以简单的实现ajax交互,避免了使用struts2-dojo-plugin.jar包时带来的struts2.x版本冲突问题.并且减少了使用ajax标签时需要的繁琐的配置包括web.xml ...

  4. Python搭建Web服务器,与Ajax交互,接收处理Get和Post请求的简易结构

    用python搭建web服务器,与ajax交互,接收处理Get和Post请求:简单实用,没有用框架,适用于简单需求,更多功能可进行扩展. python有自带模块BaseHTTPServer.CGIHT ...

  5. 关于文件上传的ajax交互

    首先我们来了解一下上传文件 <input type="file"> input的file常用上传类型 后缀名 MIME名称 *.3gpp audio/3gpp, vid ...

  6. jq的ajax交互封装

    jq封装的ajax,然后 在此前和此后都是很多要考虑的  ,何不 想想构思封装下. 下面: 基本上网页都存在各种ajax,使得网页变得更加易于操作. 举个长长的例子吧: <input type= ...

  7. springmvc与ajax交互常见问题

    这是我个人再编写博客系统的时候,因个人疏忽犯下的低级错误. 不过犯错是一件好事,有助于总结. 1.关于参数前加@RequestBody 如果是使用ajax交互时,必须要加上这个contentType: ...

  8. jQuery中的ajax用法案例

    什么是 AJAX? AJAX = 异步 JavaScript 和 XML(Asynchronous JavaScript and XML). 简短地说,在不重载整个网页的情况下,AJAX 通过后台加载 ...

  9. 关于ajax入门案例

    $.ajax方法 1.url: 要求为String类型的参数,(默认为当前页地址)发送请求的地址. 2.type: 要求为String类型的参数,请求方式(post或get)默认为get.注意其他ht ...

随机推荐

  1. Go中的fmt几种输出的区别和格式化方式

    在日常使用fmt包的过程中,各种眼花缭乱的print是否让你莫名的不知所措呢,更让你茫然的是各种格式化的占位符..简直就是噩梦.今天就让我们来征服格式化输出,做一个会输出的Goer. fmt.Prin ...

  2. X-Admin&ABP框架开发-设置管理

    在网站开发中,设置是不可缺少的一环,如用户设置.系统设置.甚至是租户设置等.ABP对于设置的管理已经做了很好的处理,我们可以借助巨人的力量来完成我们的冒险. ABP官网地址:https://aspne ...

  3. css常用代码块

    顶部固定导航栏 | css position: fixed; top: 0; left: 0; z-index: 9999; width: 100%; height: 48px; border-top ...

  4. mvnjar包冲突解决方法

    命令 mvn dependency:tree -Dverbose 结果: [INFO] +- com.esotericsoftware:kryo:jar:4.0.2:test [INFO] | +- ...

  5. python之闭包+装饰器

    闭包 内部函数对外部函数作用域变量的引用. 函数内的属性都是有生命周期的,都是在函数执行期间 闭包内的闭包函数私有化了变量,类似于面向对象 图片解析 示例一 https://www.bilibili. ...

  6. 洛谷 P4124 [CQOI2016]手机号码

    题意简述 求l~r之间不含前导零,至少有三个相邻的相同数字,不同时含有4和8的11位正整数的个数 题解思路 数位DP,注意在l,r位数不够时补至11位 代码 #include <cstdio&g ...

  7. java中String,StringBuffer,StringBuilder的区别

    String: 1,是字符串常量,一旦创建就不能修改.对于已经存在了的String对象的修改都是重新创建一个新的对象,然后把新的值保存进去. 2,String也是final类,不能被继承. 3,而且S ...

  8. JMeter定制Sampler

    1.背景 相信大家在使用JMeter工具测试的时候,经常会遇到自带采样器无法满足测试要求的情况.面对这种情况,通常的办法是使用万能的自定义Java Request的达到测试目的.这个方法有个弊端,只要 ...

  9. mysql5.7绿色版配置以及找不到 mysql服务问题解决

    一.下载软件 1. 进入mysql官网,登陆自己的Oracle账号(没有账号的自己注册一个),下载Mysql-5.7.17,下载地址:http://dev.mysql.com/downloads/my ...

  10. Kubernetes 再深入一点点

    kb master 运行如下容器 etcd 是 k8s 的核心, 主要负责k8s的核心数据处理及保存, 需要备份该数据,或者做集群 ,服务端口 2379(客户端服务) 2380(节点通信)kube-c ...