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

前端通过表单和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. k8s+istio:流量控制之灰度发布

    通过Kubernetes+Istio的流量控制实现灰度发布,主要演示通过流量权重实现蓝绿,通过http自定义头实现金丝雀 准备环境 k8s和istio不想自己装的话可以在云上买个按量付费集群,用完即删 ...

  2. virtualbox安装ubuntu16 LTS及其配置

    一.下载安装VirtualBox 1. 从官网下载VirtualBox,目前版本:VirtualBox 6.0.6 for Windows hosts x86/amd64 2. 下载好之后安装Virt ...

  3. 【POJ - 2229】Sumsets(完全背包)

    Sumsets 直接翻译了 Descriptions Farmer John 让奶牛们找一些数加起来等于一个给出的数N.但是奶牛们只会用2的整数幂.下面是凑出7的方式 1) 1+1+1+1+1+1+1 ...

  4. 一文读懂JS中的原型和原型链(图解)

    讲原型的时候,我们应该先要记住以下几个要点,这几个要点是理解原型的关键: 1.所有的引用类型(数组.函数.对象)可以自由扩展属性(除null以外). 2.所有的引用类型都有一个’_ _ proto_ ...

  5. rtags——node.js+redis实现的标签管理模块

    引言在我们游览网页时,随处可见标签的身影: 进入个人微博主页,可以看到自己/他人的标签,微博系统会推送与你有相同标签的人 游览博文,大多数博文有标签标记,以说明文章主旨,方便搜索和查阅 网上购物,我们 ...

  6. 【原创实践】U大师启动安装windows XP

    1:使用U大师3.0版制作启动U盘,拷贝windows xp或者win7的原版安装iso(zh-hans_windows_xp_professional_with_service_pack_3_x86 ...

  7. bottombar——Fragment

    首先是依赖   compile 'com.hjm:BottomTabBar:1.1.1' 下面是activity.xml文件 <RelativeLayout xmlns:android=&quo ...

  8. Navicat连接MYsql报错

    在Windows中安装mysql8后,使用Navicat连接数据库是出现“ Client does not support authentication protocol requested by s ...

  9. 构建企业级数据湖?Azure Data Lake Storage Gen2不容错过(上)

    背景 相较传统的重量级OLAP数据仓库,“数据湖”以其数据体量大.综合成本低.支持非结构化数据.查询灵活多变等特点,受到越来越多企业的青睐,逐渐成为了现代数据平台的核心和架构范式. 数据湖的核心功能, ...

  10. 实现API管理系统的几个重要关键词

    管理API的需求源自于Web API开展业务.从2006年开始,然后逐渐成熟,并在2016年之前进入市场.无论是通过代理现有API的管理网关.本身作为用于部署API本身的网关的一部分,还是作为连接层在 ...