前端基础知识---Ajax
1 Ajax、XML简介
1.1 Ajax简介
Ajax是异步的js和XML,无刷新获取数据
优点:(1)无刷新页面与服务端通信
(2)可根据用户事件更新部分页面
缺点:(1)无浏览历史,不可后退
(2)存在跨域问题
(3)SEO不友好
1.2 XML简介
XML可拓展标记语言,设计于传输和存储数据,现已被JSON替代
2 HTTP协议
约定了服务器和浏览器之间的互相通信的规则。(请求报文和响应报文)
请求报文:(POST请求才有请求体,GET的请求体为空)
响应报文:
html是放在响应体中的。
浏览器在接受到服务器发来的响应体之后,提取html内容进行解析,再渲染在页面中。
2 案例
2.1 GET.html
<style>#result{width: 200px;height:100px;border: solid 1px #989898;}
</style><body><button>点击发送请求</button><div id="result"></div>
</body><script>//获取button元素const btn = document.getElementsByTagName('button')[0]const result = document.getElementById('result')//绑定事件btn.onclick = function(){//1.创建对象const xhr = new XMLHttpRequest();//2.初始化 设置请求方法和urlxhr.open('GET','http://127.0.0.1:8000/server?a=100&&b=200')//3.发送xhr.send()//4.事件绑定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.getResponseHeader())//所有响应头// }//设置result的文本result.innerHTML = xhr.response;}}}
</script>
2.2 POST.html
<style>#result{width: 200px;height: 100px;border: solid 1px #939393;}
</style>
<body><div id="result"></div>
</body>
<script>//获取元素对象const result = document.getElementById('result');//绑定事件result.addEventListener("mouseover",function(){//1.创建对象const xhr = new XMLHttpRequest();//2.初始化 设置类型与urlxhr.open('POST','http://127.0.0.1:8000/server');//设置请求头xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')//3.发送xhr.send('123456')//4.事件绑定xhr.onreadystatechange = function(){if(xhr.readyState ===4){if(xhr.status >=200&&xhr.status<300){result.innerHTML = xhr.response;}}}})</script>
2.3 JSON.html
<style>#result{width: 200px;height: 100px;border: solid 1px #898989;}
</style>
<body><div id="result"></div>
</body><script>//绑定键盘按下事件window.onkeydown = function(){//创建对象const xhr = new XMLHttpRequest();//初始化xhr.open('GET','http:127.0.0.1:8000/json-server')//发送xhr.send();//事件绑定xhr.onreadystatechange = function(){if(xhr.readyState === 4){ // 请求完成if(xhr.status >= 200 && xhr.status < 300){ // 响应成功// 解析后端返回的JSON字符串为对象const data = JSON.parse(xhr.responseText);// 将数据渲染到页面result.innerHTML = data.name;}}
}}
</script>
sever.js
const express = require('express') //引入express包
const app = express(); //创建应用对象
app.get('/server',(req,res)=>{ //创建路由规则//设置响应头,允许跨域res.setHeader('Access-Control-Allow-Origin','*')res.send('hello ajax')
});
app.post('/server',(req,res)=>{ //创建路由规则//设置响应头,允许跨域res.setHeader('Access-Control-Allow-Origin','*')res.send('hello ajax post')
});
app.all('/json-server',(req,res)=>{ //创建路由规则//设置响应头,允许跨域res.setHeader('Access-Control-Allow-Origin','*')//响应一个数据const data = {name:'aguigu'}//对对象进行字符串转换let str = JSON.stringify(data)res.send(str)
});app.listen(8000,()=>{ //监听console.log('服务器已经启动,8000端口监听中')
})
3 IE缓存问题
xhr.open('POST','http://127.0.0.1:8000/ie?t='+Date.now());
每次都不一样,就不会拿到缓存结果
4 请求超时与网络异常问题
html
//超时2s设置xhr.timeout = 2000;//超时回调xhr.ontimeout = function(){alert('网络异常,请稍后重试!')}//网络异常回调xhr.onerror = function(){alert('你的网络似乎出现了一些问题')
js
app.get('/delay',(req,res)=>{ //创建路由规则//设置响应头,允许跨域res.setHeader('Access-Control-Allow-Origin','*')setTimeout(()=>{res.send('延时响应')},3000)});
5 取消重复请求(设置标识变量)
abort()
//标识变量let isSending = false;// 初始值为 false,表示“当前没有正在发送的 AJAX 请求”btns[0].onclick = function(){if(isSending) x.abort(); //如果有ajax请求正在发送,则终止操作x = new XMLHttpRequest(); //终止操作后,创建新对象//修改标识变量isSending = true;x.open('GET','http://127.0.0.1:8000/delay')x.send();x.onreadystatechange = function(){if(x.readyState ===4){//修改标识变量isSending = false;}}}
6 jQuery发送Ajax请求
(1)引入jQuery
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
(2)最基础的jQuery方法
$.ajax({url: '请求的服务器地址', // 必选,如 'http://localhost:8000/data'type: '请求方法', // 可选,默认 'GET',常用 'GET'/'POST'data: '要发送的数据', // 可选,如 {name: '张三', age: 20} 或 'name=张三&age=20'dataType: '预期的响应数据类型', // 可选,如 'json'(自动解析JSON)、'html'、'text'success: function(res) { // 可选,请求成功后的回调函数,res 是服务器返回的数据console.log('请求成功', res);},error: function(xhr) { // 可选,请求失败后的回调函数,xhr 是错误信息对象console.log('请求失败', xhr);},timeout: 3000 // 可选,超时时间(毫秒),超过时间则触发 error
});
7 同源策略(来自于同一个服务器)
同源:协议、域名、端口号必须完全相同(Ajax默认遵循同源策略)