当前位置: 首页 > news >正文

前端实战-AJAX

引言

这份HTML文档是一个完整的AJAX学习示例,展示了多种AJAX请求方式和相关问题的解决方案。AJAX (Asynchronous JavaScript and XML) 是一种在不重新加载整个页面的情况下,与服务器交换数据并更新部分网页的技术。

效果呈现

源码

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>AJAX GET 请求</title><style>#resultget {width: 500px;height:100px;border:solid 1px #000000;}#resultpost {width: 500px;height:100px;border:solid 1px #004b35;}#resultjson {width: 500px;height:100px;border:solid 1px #198722bd;}#resultIE {width: 500px;height:100px;border:solid 3px #bbb102;}#resulttimeout{width: 500px;height:100px;border:solid 3px #b62b04;}#resultcancel{width: 500px;height:100px;border:solid 3px #0077be;}</style></head>
<body><!-- GET请求部分 --><div><h1>AJAX GET 请求</h1><p>通过 XMLHttpRequest 对象发送 GET 请求,获取服务器数据。</p><button id="btnget">发送请求</button><div id="resultget"></div><script src="./get.js"></script></div><!-- POST请求部分 --><div><h1>AJAX POST 请求</h1><p>通过 XMLHttpRequest 对象发送 POST 请求,提交数据到服务器。</p><button id="btnpost">鼠标移到框内</button><div id="resultpost"></div><script src="./post.js"></script></div><!-- JSON 数据解析 --><div><h1>演示服务端响应JSON数据</h1><p>通过 XMLHttpRequest 对象发送 GET 请求,获取JSON数据。</p><button id="btnjson">发送请求</button><div id="resultjson"></div><script src="./jsontest.js"></script></div><!-- 解决IE浏览器缓存问题 --><div><h1>解决IE浏览器缓存问题</h1><p></p><button id="btnIE">点击发送请求</button><div id="resultIE"></div><script src="./problem.js"></script></div><!-- 解决请求超时与服务器异常 --><div><h1>解决请求超时与服务器异常</h1><p></p><button id="btntimeout">点击发送请求</button><div id="resulttimeout"></div><script src="./timeout.js"></script></div><!-- 发送请求和取消请求 --><div><h1>发送请求和取消请求</h1><p>通过 XMLHttpRequest 对象发送 GET 请求,获取服务器数据。</p><button id="btnsend">发送请求</button><button id="btncancel">取消请求</button><div id="resultcancel"></div><script src="./cancel.js"></script></div><!-- 解决重复请求问题 --><div><h1>解决重复请求问题</h1><p>通过 XMLHttpRequest 对象发送 GET 请求,获取服务器数据。</p><button id="btnrepeat">发送请求</button><div id="resultrepeat"></div><script src="./repeat.js"></script></div>
</body>
</html>

js部分

get.js

const btn = document.getElementById('btnget');
const resultget = document.getElementById('resultget');
//绑定事件
btn.onclick = () => {console.log('发送请求成功');//创建 XMLHttpRequest 对象const xhr = new XMLHttpRequest();//初始化 设置请求方法和urlxhr.open('GET', 'http://127.0.0.1:8000/server?a=100&b=200&c=300');// 发送请求xhr.send();// 事件绑定,处理服务端返回的结果// on when 当... 的时候//readyState属性表示xhr对象的状态,0表示请求未初始化,1表示服务器连接已建立,2表示请求已接收,3表示请求处理中,4表示请求已完成,如果状态为4,说明请求已成功完成,可以进行后续操作xhr.onreadystatechange = () => {// 判断服务器返回了所有的结果if(xhr.readyState === 4){// 判断响应状态码 200 404 403 401 500if(xhr.status === 200){//处理结果 行 头 空行 体// 响应行console.log(xhr.status);//状态码console.log(xhr.statusText);//状态描述console.log(xhr.getAllResponseHeaders());//所有响应头console.log(xhr.response);//响应体//设置resultget的文本resultget.innerHTML = xhr.response;}}}
}

post.js

//获取元素对象
const result = document.getElementById("resultpost");
//绑定事件
result.addEventListener("mouseover",function(){console.log("mouseover");//创建对象const xhr = new XMLHttpRequest();//设置请求方式和请求地址xhr.open('POST','http://127.0.0.1:8000/server');//设置请求头xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');// 发送xhr.send('a=200&b=300');// 事件绑定xhr.onreadystatechange = function(){if(xhr.readyState === 4){if(xhr.status >= 200 && xhr.status < 300){//处理服务器返回的结果result.innerHTML = xhr.responseText;}}}
});

jsontest.js

const resultjson = document.getElementById('resultjson');
// 绑定键盘按下事件
window.onkeydown = function(){console.log('绑定成功');// 发送请求const xhr = new XMLHttpRequest();//设置响应体数据类型xhr.responseType = 'json';// 初始化xhr.open('GET', 'http://127.0.0.1:8000/json-server');// 发送请求xhr.send();// 事件绑定xhr.onreadystatechange = function(){if(xhr.readyState === 4){if(xhr.status === 200){// console.log(xhr.responseText);// resultjson.innerHTML = xhr.responseText; // 1.手动对数据转化// let data = JSON.parse(xhr.response);// console.log(data);// resultjson.innerHTML = data.name;//2.自动转化console.log(xhr.response);resultjson.innerHTML = xhr.response.name;}}}
}

problem.js

const btnIE = document.getElementById('btnIE');
const resultIE = document.querySelector('#resultIE');btnIE.addEventListener('click', () => {const xhr = new XMLHttpRequest();xhr.open('GET', 'http://127.0.0.1:8000/ie?t='+Date.now());xhr.send();xhr.onreadystatechange = function() {if (xhr.readyState === 4 && xhr.status === 200) { resultIE.innerHTML = xhr.response;} }});

timeout.js

const btntimeout = document.getElementById('btntimeout');
const resulttimeout = document.querySelector('#resulttimeout');btntimeout.addEventListener('click', () => {const xhr = new XMLHttpRequest();//超时设置 2sxhr.timeout = 2000;// 超时回调xhr.ontimeout = function() {resulttimeout.innerHTML = '请求超时';};// 网络异常回调xhr.onerror = function() {alert('你的网络似乎出了一点问题');};xhr.open('GET', 'http://127.0.0.1:8000/delay');xhr.send();xhr.onreadystatechange = function() {if (xhr.readyState === 4 && xhr.status === 200) { resulttimeout.innerHTML = xhr.response;} }});

cancel.js

const btnSend = document.getElementById('btnsend');
const btnCancel = document.getElementById('btncancel');
const resultCancel = document.getElementById('resultcancel');let xhr = null;let isSending = false; //是否正在发送AJAX请求btnSend.addEventListener('click', () => {//判断标识变量if(isSending) xhr.abort();//如果请求正在发送则取消该请求只发送一个请求xhr = new XMLHttpRequest();//修改标识变量的值isSending = true;xhr.open('GET', 'http://127.0.0.1:8000/delay');xhr.send();xhr.onreadystatechange = function() {if (xhr.readyState === 4 && xhr.status === 200) { // 修改标识变量isSending = false;resultCancel.innerHTML = xhr.response;} }});btnCancel.addEventListener('click', () => {xhr.abort();resultCancel.innerHTML = '请求已取消';});

服务器

const express = require('express');
//创建应用对象
const app = express();// 添加请求体解析
app.use(express.json());
app.use(express.urlencoded({ extended: true }));//创建路由规则
// 处理get请求
app.get('/server', (req, res) => {// 设置响应头res.setHeader('Access-Control-Allow-Origin', '*');res.setHeader('Access-Control-Allow-Headers', '*');// 设置响应体res.send('Great! You get it!');
});// 处理post请求
app.post('/server', (req, res) => {// 设置响应头res.setHeader('Access-Control-Allow-Origin', '*');res.setHeader('Access-Control-Allow-Headers', '*');// 设置响应体res.send('Great! You POST it!');
});// 处理json请求
app.all('/json-server', (req, res) => {// 设置响应头res.setHeader('Access-Control-Allow-Origin', '*');res.setHeader('Access-Control-Allow-Headers', '*');// 设置响应体// res.send('Great! JSON server is working!');// 响应一个数据const data = {name:'sdwhebdsdfd'};//对对象进行一个字符串的转换let str = JSON.stringify(data);res.send(str);
});// 处理IE请求
app.get('/ie', (req, res) => {// 设置响应头res.setHeader('Access-Control-Allow-Origin', '*');res.setHeader('Access-Control-Allow-Headers', '*');// 设置响应体res.send('Its IE Qusetion!');
});// 处理错误请求
app.get('/delay', (req, res) => {// 设置响应头res.setHeader('Access-Control-Allow-Origin', '*');res.setHeader('Access-Control-Allow-Headers', '*');setTimeout(() => {// 设置响应体res.send('延时响应');}, 3000);});//JQuery请求
app.all('/jquery-server', (req, res) => {// 设置响应头res.setHeader('Access-Control-Allow-Origin', '*');res.setHeader('Access-Control-Allow-Headers', '*');// 设置响应体const data ={name:'JQuery发送的请求'};res.send(JSON.stringify(data));//res.send('Its JQuery Qusetion!');
}); // Axios请求
app.all('/axios-server', (req, res) => {// 设置响应头res.setHeader('Access-Control-Allow-Origin', '*');res.setHeader('Access-Control-Allow-Headers', '*');// 设置响应体const data ={name:'axios发送的请求'};res.send(JSON.stringify(data));//res.send('Its Axios Qusetion!');
}); // 404处理
app.use((req, res) => {res.status(404).send('Not Found');
});//监听端口启动服务
app.listen(8000, () => {console.log('Server is running on port 8000');
});

相关文章:

  • ubuntu 22.04 安装和配置 mysql 8.0,设置开机启动
  • 力扣热题100——矩阵
  • Spring Boot 断点续传实战:大文件上传不再怕网络中断
  • 74.搜索二维矩阵
  • 学习海康VisionMaster之垂线查找
  • 电控---SWD协议
  • Python进程与线程的深度对比
  • 【仿Mudou库one thread per loop式并发服务器实现】HTTP协议模块实现
  • Java中如何创建操作线程
  • 【Tip】MathType中输入空格符号
  • Indocia启动$INDO代币预售第一阶段 - 100% 社区安全,具有真正的盈利潜力
  • 【Python】如何查找电脑上的Python解释器
  • 【回眸】error: failed to compile `xxxxxx`重装rust环境
  • Unocss 类名基操, tailwindcss 类名
  • 【错误记录】Windows 命令行程序循环暂停问题分析 ( 设置 “ 命令记录 “ 选项 | 启用 “ 丢弃旧的副本 “ 选项 | 将日志重定向到文件 )
  • SpringBoot和微服务学习记录Day3
  • Java 自动装箱与拆箱:基本数据类型与包装类的转换
  • 【Java面试笔记:基础】1.谈谈你对Java平台的理解?
  • pip永久换镜像地址
  • 解决Chrome浏览器访问https提示“您的连接不是私密连接”的问题
  • 水利部启动干旱防御Ⅳ级响应,指导广西陕西抗旱保供保灌
  • 平均25岁,天津茱莉亚管弦乐团进京上演青春版《春之祭》
  • 复旦大学附属中山医院也有儿科了,门诊将于下月底开业
  • 【社论】地铁读书人也是一道城市风景
  • 纪念沈渭滨︱沈渭滨先生与新修《清史》
  • 十大券商看后市|A股下行波动风险有限,震荡中有望逐步抬升