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">×</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交互案例的更多相关文章
- ThinkPHP中使用ajaxReturn进行ajax交互
以管理员登录为例来介绍下$this->ajaxReturn与模板页进行ajax交互使用方法 首先看PHP控制器的处理,在application/Admin/Controller/LoginCon ...
- struts2 的验证框架validation如何返回json数据 以方便ajax交互
struts2 的验证框架validation简单,好用,但是input只能输出到jsp页面通过struts2的标签<s:fielderror />才能取出,(EL应该也可以). 如果使 ...
- struts2中使用json插件实现ajax交互
json插件可以简单的实现ajax交互,避免了使用struts2-dojo-plugin.jar包时带来的struts2.x版本冲突问题.并且减少了使用ajax标签时需要的繁琐的配置包括web.xml ...
- Python搭建Web服务器,与Ajax交互,接收处理Get和Post请求的简易结构
用python搭建web服务器,与ajax交互,接收处理Get和Post请求:简单实用,没有用框架,适用于简单需求,更多功能可进行扩展. python有自带模块BaseHTTPServer.CGIHT ...
- 关于文件上传的ajax交互
首先我们来了解一下上传文件 <input type="file"> input的file常用上传类型 后缀名 MIME名称 *.3gpp audio/3gpp, vid ...
- jq的ajax交互封装
jq封装的ajax,然后 在此前和此后都是很多要考虑的 ,何不 想想构思封装下. 下面: 基本上网页都存在各种ajax,使得网页变得更加易于操作. 举个长长的例子吧: <input type= ...
- springmvc与ajax交互常见问题
这是我个人再编写博客系统的时候,因个人疏忽犯下的低级错误. 不过犯错是一件好事,有助于总结. 1.关于参数前加@RequestBody 如果是使用ajax交互时,必须要加上这个contentType: ...
- jQuery中的ajax用法案例
什么是 AJAX? AJAX = 异步 JavaScript 和 XML(Asynchronous JavaScript and XML). 简短地说,在不重载整个网页的情况下,AJAX 通过后台加载 ...
- 关于ajax入门案例
$.ajax方法 1.url: 要求为String类型的参数,(默认为当前页地址)发送请求的地址. 2.type: 要求为String类型的参数,请求方式(post或get)默认为get.注意其他ht ...
随机推荐
- 转载 | SVG向下兼容优雅降级方法
本文引自:http://www.zhangxinxu.com/wordpress/2013/09/svg-fallbacks/ 1.svg image标签降级技术 <svg width=&quo ...
- String与new String()的区别
JVM为了提升性能和减少内存开销,避免字符串的重复创建,维护了一块特殊的内存空间——字符串实例池. String赋值的两种方式. 1.String str = "test"; 以这 ...
- 如何删除GIT仓库中的敏感信息
如何删除GIT仓库中的敏感信息 正常Git仓库中应该尽量不包含数据库连接/AWS帐号/巨大二进制文件,否则一旦泄漏到Github,这些非常敏感信息会影响客户的信息安全已经公司的信誉.公司可能其它还有相 ...
- idea快速生成实体类
1.打开idea的视图,选择Database 2.选择对应的数据库[这里是mysql为例] 3.输入自己对应的内容,输入完成可点击Test Connection进行测试,成功SUCCESS 4.点击确 ...
- 《NVM-Express-1_4-2019.06.10-Ratified》学习笔记(1)
材料说明: 文档<NVM-Express-1_4-2019.06.10-Ratified.pdf>来自于NVMe网站:https://nvmexpress.org/ 笔记目的是学习NVMe ...
- ajax后台处理响应(java)
public static final void sendAsJson(HttpServletResponse response, String str) { response.setContentT ...
- NMS的python实现
https://blog.csdn.net/a1103688841/article/details/89711120
- 章节十六、5-TestNG高级功能--Part2
一.测试用例的依赖关系--->(dependsOnMethods = {"依赖方法名"}) 1.在实现自动化的过程中,有些测试用例必须在其它测试用例执行之后才能运行,两者之间 ...
- 设计模式(C#)——01单例模式
推荐阅读: 我的CSDN 我的博客园 QQ群:704621321 为什么要学习设计模式呢?我以前也思考过很多次这个问题,现在也还困惑.为什么我最后还是选择了学设计模式呢?因为在游戏中 ...
- FZU 2235
中文题,题意略. 这个题点少坐标范围大,直接离散化后建图搞. 这个题目卡vector,真是一脸懵逼............ #include<stdio.h> #include<st ...