Ajax
Ajax简介
Ajax即Asynchronous Javascript And XML(异步JavaScript和[XML] [HTML]或 [XHTML] CSS, [JavaScript][DOM], XML, [XSLT] 以及最重要的[XMLHttpRequest] 使用Ajax技术网页应用能够快速地将增量更新呈现在[用户界面]上,而不需要重载(刷新)整个页面,这使得程序能够更快地回应用户的操作。
XML简介
W3school:学习网站。 https://www.w3school.com.cn/xml/xml_intro.asp
Ajax的特点
##### Ajax的优点:
- 可以无需刷新页面与服务端进行交互
- 允许根据用户的时间来更新部分的页面内容
##### Ajax的缺点:
- 没有浏览历史、不能回退
- 存在跨域问题
- SEO不友好
HTTP协议
HTTP:超文本传输协议。协议规定了浏览器和万维网服务器之间相互通信的规则、约定。
请求报文
格式与参数:
行 GET / URL /HTTP
头 HOST:xxx.com
Cookie:name=lihui
Content-type:application/x-www-form-urlencoded
User-Agent:chrome 84
空行
体 username=admin&password=admin
响应报文
行 HTTP/1.1 200 OK
头 Content-type=text/html;charset=utf-8
Content-length:2048
Content-encoding:zip
空行
体 <html>
<head>
</head>
<body>
<h1>lihui</h1>
</body>
</html>
状态码
404
403
401
500
…
node.js的安装
官网下载->一直下一步安装->安装成功后->node -v检查是否安装成功。
express框架的安装:npm i express
express框架的使用
const { response } = require('express');
const express = require('express');
const { request } = require('http');
const app = express();
app.get('/',(request,response)=>{
response.send('Hello Express')
})
app.listen(8080,()=>{
console.log("服务已经启动,8080端口监听中~~~~")
})
express 框架的运行
PS E:\practice_vue\Vue\express> node express.js
服务已经启动,8080端口监听中~~~~
浏览器响应结果:
1 个请求
已传输 177 B
13 B 项资源
完成用时:3 毫秒
DOMContentLoaded:24 毫秒
加载时间:26 毫秒
请求网址: http://127.0.0.1:8080/
请求方法: GET
状态代码: 304 OK
远程地址: 127.0.0.1:8080
引荐来源网址政策: strict-origin-when-cross-origin
测试Ajax发送get请求
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ajax发送get请求</title>
<style>
#result{
width: 200px;
height: 100px;
border: solid 1px #90b;
}
</style>
</head>
<body>
<button>点我发送请求</button>
<div id="result"></div>
</body>
</html>
const { response } = require('express');
const express = require('express');
const { request } = require('http');
const app = express();
app.get('/',(request,response)=>{
response.setHeader('Access-controll-Allow-Origin','*')
response.send('Hello Express')
})
app.listen(8080,()=>{
console.log("服务已经启动,8080端口监听中~~~~")
})
从新启动js报错:(npm express.js)
Error: listen EADDRINUSE: address already in use :::8080
at Server.setupListenHandle [as _listen2] (net.js:1318:16)
at listenInCluster (net.js:1366:12)
at Server.listen (net.js:1452:7)
at Function.listen (E:\practice_vue\node_modules\express\lib\application.js:635:24)
at Object.<anonymous> (E:\practice_vue\Vue\express\express.js:21:5)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
Emitted 'error' event on Server instance at:
at emitErrorNT (net.js:1345:8)
at processTicksAndRejections (internal/process/task_queues.js:80:21) {
code: 'EADDRINUSE',
errno: -4091,
syscall: 'listen',
address: '::',
port: 8080
}
报错信息描述,端口被占用了,将启动的服务停止从新运行即可。
浏览器:Access-controll-Allow-Origin: *
完整代码
const { response } = require('express');
const express = require('express');
const { request } = require('http');
const app = express();
app.get('/express',(request,response)=>{
response.setHeader('Access-Control-Allow-Origin','*')
response.send('Hello Express')
})
app.listen(8000,()=>{
console.log("服务已经启动,8000端口监听中~~~~")
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ajax发送get请求</title>
<style>
#result {
width: 200px;
height: 100px;
border: solid 1px #90b;
}
</style>
</head>
<body>
<button>点我发送请求</button>
<div id="result"></div>
<script>
const btn = document.getElementsByTagName('button')[0];
const result = document.getElementById('result');
btn.onclick = function () {
const xhr = new XMLHttpRequest();
xhr.open('GET', 'http://127.0.0.1:8000/express');
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
console.log(xhr.status)
console.log(xhr.statusText)
console.log(xhr.getAllResponseHeaders());
console.log(xhr.response);
result.innerHTML = xhr.response;
} else {
}
}
}
}
</script>
</body>
</html>
Ajax-Get设置请求参数
?a=100&b=200
xhr.open('GET', 'http://127.0.0.1:8000/express?a=100&b=200');
Ajax发送post请求
const { response } = require('express');
const express = require('express');
const { request } = require('http');
const app = express();
app.post('/express',(request,response)=>{
response.setHeader('Access-Control-Allow-Origin','*')
response.send('Hello Express')
})
app.listen(8000,()=>{
console.log("服务已经启动,8000端口监听中~~~~")
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ajax发送post请求</title>
<style>
#result{
width: 200px;
height: 200px;
border: 1px solid red;
}
</style>
</head>
<body>
<div id="result">
</div>
<script>
const result = document.getElementById('result');
result.addEventListener('mouseover',function(){
const xhr = new XMLHttpRequest();
xhr.open('post','http://127.0.0.1:8000/express');
xhr.send();
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if(xhr.status >= 200 & xhr.status < 300){
result.innerHTML = xhr.response;
}
}
}
})
</script>
</body>
</html>
Ajax-Post设置请求参数
xhr.open('post','http://127.0.0.1:8000/express');
xhr.send('a=100&b=200&c=300');
或
xhr.send('a:100&b:200&c:300');
或
xhr.send('123456');
Ajax设置请求头
xhr.setRequestHeader('预定义','value')
xhr.setRequestHeader('自定义','value')
response.setHeader('Access-Control-Allow-Headers','*')
response.setHeader('Access-Control-Allow-Headers','*')
app.all('/express',(request,response)=>{
response.setHeader('Access-Control-Allow-Origin','*')
response.send('Hello Express')
})
Ajax请求服务端响应JSON数据
两种方式:手动转换和自动转换
const { response } = require('express');
const express = require('express');
const { request } = require('http');
const app = express();
app.all('/express',(request,response)=>{
response.setHeader('Access-Control-Allow-Origin','*')
response.setHeader('Access-Control-Allow-Headers','*')
const data = {
name:'lihui',
}
let str = JSON.stringify(data);
response.send(str)
})
app.listen(8000,()=>{
console.log("服务已经启动,8000端口监听中~~~~")
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#result{
width: 200px;
height: 200px;
border: 1px solid red;
}
</style>
</head>
<body>
<div id="result"></div>
<script>
const result = document.getElementById('result')
window.onkeydown = function(){
const xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.open('GET','http://127.0.0.1:8000/express');
xhr.send();
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if(xhr.status >= 200 && xhr.status < 300){
let data = JSON.parse(xhr.response);
console.log(data);
result.innerHTML = xhr.response.name;
}
}
}
}
</script>
</body>
</html>
自动重启工具的安装
这个在安装vscode的时候也可以选择:
安装命令(npm install -g nodemon )
浏览器的缓存问题:(浏览器会对Ajax发送的数据进行缓存,有时候,测试更新时,会造成干扰。)
Ajax请求超时与网络异常处理
setTimeout(()=>{
respon.send('延时响应');
},3000)
xhr.timeout = 2000;
xhr.ontimeout = function(){
alert('网络超时,请重试~~~');
}
xhr.onerror = function(){
alert('你的网络好像出现了问题~~~');
}
Ajax取消请求
const btns = document.querySelectorAll('button');
btns[0].onclick = function(){
const x = new XMLHttpRequest();
x.open('GET',"http://127.0.0.1:8000/express");
x.send();
}
btns[1].onclick = function(){
alert("手动取消Ajax请求")
x.abort();
}
Ajax重复请求发送问题
用户频繁发送请求,服务器压力就大,解决服务器压力大的问题。
let isSending = false;
const btns = document.querySelectorAll('button');
btns[0].onclick = function(){
if(isSending) x.abort();
const x = new XMLHttpRequest();
x.open('GET',"http://127.0.0.1:8000/express");
x.send();
x.onreadystatechange = function(){
if(x.readyState === 4){
isSending = false;
}
}
}
jQuery中的Ajax请求
搜索bootcnd 引入jQuery
https://cdn.bootcdn.net/ajax/libs/jquery/3.6.1/jquery.js
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.1/jquery.js"></script>
<div class="container">
<h2 class="page-header">
jQuery发送Ajax请求
</h2>
<button class="btn btn-primary">
get
</button>
<button class="btn btn-danger">
post
</button>
<button class="btn btn-info">
通用Ajax
</button>
</div>
<script>
$('button').eq(0).click(function(){
$.get('http://127.0.0.1:8000/express',{a:100,b:200},function(data){
console.log(data);
},'json');
})
$('button').eq(1).click(function(){
$.get('http://127.0.0.1:8000/express',{a:100,b:200},function(data){
console.log(data);
},'json')
})
$('button').eq(2).click(function(){
$.ajax({
url:'http://127.0.0.1:8000/express',
data:{a:100,b:200},
type:'GET',
dataType:'json',
sucess.function(data){
console.log("成功~~~~");
}
error.function(data){
console.log("出错了~~~")
}
headers:{
c:300,
d:400
}
})
})
</script>
jQuery学习文档
https://jquery.cuishifeng.cn/
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4gEBNLrY-1662470493263)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\1662465349297.png)]
Axios发送Ajax请求
学习网址
https://github.com/axios/axios
使用安装命令:(npm install axios)
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.27.2/axios.js"></script>
https://www.axios-http.cn/docs/intro
<button>GET</button>
<button>POST</button>
<button>AJAX</button>
<script>
const btns = document.querySelectorAll('button');
btns[0].onclick = function(){
axios.get('http://127.0.0.1:8000/express',{
params:{
id:100,
vip:7
},
headers:{
name:'lihui',
age:18
}
}).then(value=>{
console.log(value);
});
}
btns[0].onclick =function(){
axios.post('/express',
{
username:'lihui',
password:'lihui',
},{
params:{
id:200,
vip:1
},
headers:{
heigth:100,
weight:90,
}
})
}
</script>
axios通用方式发送Ajax请求
btns[2].onclick = function(){
axios({
method:'POST',
url:'/express',
params:{
name:'lihui',
level:19
},
headers:{
a:100,
b:200
},
data:{
username:'admin',
password:'123456'
}
}).then(response=>{
console.log(response);
console.log(response.status);
console.log(response.statusTest);
console.log(response.headers);
console.log(response.data);
})
}
axios通过函数发送Ajax请求
<button>ajax请求</button>
<script>
const btn = document.querySelector('button');
btn.onclick = function(){
fetch('http:127.0.0.1:8000/express?vip=10',{
method:'POST',
headers:{
name:'lihui'
},
body:'username = adming & password = admin',
}).then(response=>{
return response.text();
}).then(response=>{
console.log(response);
});
}
</script>
跨域
同源策略
Ajax默认遵循同源策略。
同源:协议、域名、端口号必须完全相同。
违背了同源策略就是跨域。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>首页</title>
</head>
<body>
<h1>lihui</h1>
<button>点击获取用户数据</button>
<script>
const btn = document.querySelector('button');
btn.onclick = function(){
const x = new XMLHttpRequest();
x.open('GET','/data')
x.send();
x.onreadystatechange = function(){
if(x.readyState === 4){
if(x.status >= 200 && x.status <300){
console.log(x.response);
}
}
}
}
</script>
</body>
</html>
const { response } = require('express');
const express = require('express');
const { request } = require('http');
const app = express();
app.get('/home',(request,response)=>{
response.sendFile(__dirname+'/index.html');
});
app.get('/data',(request,response)=>{
response.send("用户数据发送成功~~~");
})
app.listen(9000,()=>{
console.log('服务已经启动了');
})
如何解决跨域
- JSONP:仅支持get请求
- CORS:跨域资源共享。
Ajax的实战
…
|