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

前端通过表单和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. python基础--基于套接字进行文件传输、异常处理、socketserver模块

    异常处理: 什么是异常处理: 程序在运行过程中出现了不可预知的错误,并且该错误没有对应的处理机制,那么就会以异常的形式表现出来,造成的影响就是整个程序无法再正常运行 异常的结构: 异常的类型.异常的信 ...

  2. JS和C#.NET获取客户端IP

    我们经常在项目中会遇到这种需要获取客户端真实IP的需求,其实在网上也能随便就能查到各种获取的方法,我也是在网上查了加上了自己的实践,说一下自己在实践后的感受,基本上网上大部分都是用JS的方法来获取客户 ...

  3. 解读 PHP 的 P++提案

    解读 PHP 的 P++提案 周末看到一篇文章说 PHP 创始人提议将 PHP 拉出新分支,创建 P++ 语言.随后阅读了一下 Zeev Suraski 发起的这个邮件列表,大致了解了一下,这里做个解 ...

  4. Hadoop - YARN Introduce

    YARN Introduce 1. MapReduce1.0缺陷 (1)存在单点故障 (2)JobTracker"大包大揽"导致任务过重(任务多时内存开销大,上限4000节点) ( ...

  5. Codeforces 436D Pudding Monsters

    题意简述 开始有无限长的一段格子,有n个格子种有布丁怪兽,一开始连续的布丁怪兽算一个布丁怪兽. 每回合你可以将一个布丁怪兽向左或右移动,他会在碰到第一个布丁怪兽时停下,并与其合并. 有m个特殊格子,询 ...

  6. 阿里、网易和腾讯面试题 C/C++

    一.线程.锁 1.Posix Thread互斥锁 线程锁创建 a.静态创建 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; b.动态创建 pthr ...

  7. windows 下 ctags 安装以及 tags 目录创建

    最近处理 .as 格式代码,需要转换成 c# 格式, 用 VS 查看,无法跳转,十分蛋疼,又用起了好久没用的 VIM,配置 tags 文件,实现自动跳转. 1.下载ctag文件http://ctags ...

  8. NFS Debian 服务器,CentOS 客户端

    0x00 事件 最近买了一台 500G 储存的 VPS,但是与国内的连接.下载速度都比较差,于是想了个「曲线救国」的方式. 另外有一台 GIA 与 VPS-500G 通信比较理想,同时 GIA 与国内 ...

  9. Day 01--选题与设计(一)

    1.第一天我们主要确定了软件课设的项目,做一个学校内食堂订送餐的微信小程序.我们大体的设计思路是:可以实现学生身份的认证,幷使学生们能自行选择校园内的食堂,挑选各个食堂各个窗口菜谱上可以选择的菜,选择 ...

  10. spring事务在实际项目开发中的使用

      一, 事务的一些基础知识简单回顾一下,讲的不是很深入,网上博客很多. 1,关于事务的四大特性:原子性.隔离性.一致性.隔离性 本文不再赘述: 2,事务的隔离级别:读未提交,读已提交,可重复读,串行 ...