目录
一、Ajax特点
优点:
1.可以无需刷新页面与服务器进行通信
2.允许根据用户事件来更新部分页面内容
缺点:
1.没有浏览历史,不能回退
2.存在跨域问题(同源)
3.SEO(搜索引擎优化)不友好
二、HTTP协议
1.请求报文
1.1请求行
请求类型:GET、POST
url路径
HTTP协议版本
1.2请求头
host: mting.com
cookie: name = zmt
content - type: application / x - www - form - urlencoded
1.3请求空行(necessary)
1.4请求体
如果是get请求,请求体为空
如果是post请求, 请求体可为空可不为空
2.响应报文
响应行
HTTP协议版本
响应状态码(200, 404, 403, 500, 401等)
响应状态字符串
响应头
响应空行
响应体
3.get请求
const xhr = new XMLHttpRequest();
// 初始化,设置请求方法和url
xhr.open('GET', 'http://127.0.0.1:8000/server');
4.post请求
const xhr = new XMLHttpRequest();
// 初始化,设置请求方法和url
xhr.open('POST','http://127.0.0.1:8000/server');
三、原生Ajax
1.express基本使用
const express = require('express');
// 2.创建应用对象
const app = express();
// 3.创建路由规则
// request是对请求报文的封装
// response是对响应报文的封装
app.get('/',(request,response)=>{
response.setHeader('Access-Control-Allow-Origin')
// 设置响应
response.send('HELLO EXPRESS')
});
app.all('/delay',(request,response)=>{
response.setHeader('Access-Control-Allow-Origin','*')
// 设置响应
setTimeout(()=>{
response.send('HELLO EXPRESS')
},3000);
});
// 4.监听端口启动服务
app.listen(8000,()=>{
console.log('服务已经启动,8000端口监听中...');
})
2.ajax请求基本步骤
1.创建对象
2.初始化 设置请求方法和url
3.发送
4.事件绑定 处理服务端返回的结果
3.ajax方式get请求
<script>
const btn = document.getElementsByTagName('button')[0];
const result = document.getElementById('result');
btn.onclick = function () {
// 1.创建对象
const xhr = new XMLHttpRequest();
// 初始化,设置请求方法和url
xhr.open('GET', 'http://127.0.0.1:8000/server?');
// 3.发送
xhr.send();
// 4.事件绑定 处理服务端返回的结果
// on when 当……时候
// readyState 是xhr对象中的属性,表式状态0 1 2 3 4
// change 改变
xhr.onreadystatechange = function () {
// 判断响应状态码 200 404 403 401 500
if (xhr.readyState === 4) {
// 判断响应状态码 200 404 403 401 500
// 2xx 成功
if (xhr.status >= 200 && xhr.status < 300) {
// 处理结果 行 头 空行 体
// 1.响应行
// console.log(xhr.status);//状态码
// console.log(xhr.statusText);//状态字符串
// console.log(xhr.getAllResponseHeaders);//所有响应头
// console.log(xhr.response);//响应体
result.innerHTML = xhr.response;
} else {
}
}
}
}
</script>
4.ajax发送post请求
<script>
const btn = document.getElementsByTagName('button')[0];
const result = document.getElementById('result');
result.addEventListener('mouseover',function(){
// 1.创建对象
const xhr = new XMLHttpRequest();
// 初始化,设置请求方法和url
xhr.open('POST','http://127.0.0.1:8000/server');
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.setRequestHeader('name','zmt')
// 3.发送
xhr.send('a=100&b:200')
// xhr.send('a:100&b:300');
// 4.事件绑定 处理服务端返回的结果
// on when 当……时候
// readyState 是xhr对象中的属性,表式状态0 1 2 3 4
// change 改变
xhr.onreadystatechange = function(){
// 判断响应状态码 200 404 403 401 500
if(xhr.readyState === 4){
// 判断响应状态码 200 404 403 401 500
// 2xx 成功
if(xhr.status >= 200 && xhr.status <300){
result.innerHTML = xhr.response;
}
}
}
});
</script>
5.服务端响应json数据
<script>
const result = document.querySelector('.result');
window.onkeydown = function(){
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 && xhr.status < 300){
console.log(xhr.response);
result.innerHTML = xhr.response.name;
}
}
}
}
</script>
6.IE浏览器缓存问题
解决方法: 在url路径最后加上时间戳,他就不会走缓存路线
7.网络异Ajax请求超时与常处理
<script>
const btn = document.querySelector('button');
const result = document.querySelector('.result');
btn.addEventListener('click',function(){
// console.log('test');
const xhr = new XMLHttpRequest();
// 超时设置2s设置
xhr.timeout = 2000;
// 超时回调
xhr.ontimeout = function(){
alert('网络异常,请稍后重试!');
}
// 网络异常问题
xhr.onerror = function(){
alert('您的网络似乎出了一些问题!');
}
xhr.open('GET','http://127.0.0.1:8000/delay');
xhr.send();
xhr.onreadystatechange = function(){
if(xhr.readyState === 4) {
if(xhr.status >= 200 && xhr.status < 300) {
result.innerHTML = xhr.response;
}
}
}
})
</script>
8.取消请求
<body>
<button>点击发送</button>
<button>点击取消</button>
<script>
const btns = document.querySelectorAll('button');
let x = null;
btns[0].onclick = function(){
x = new XMLHttpRequest();
x.open('GET','http://127.0.0.1:8000/delay');
x.send();
}
// abort
btns[1].onclick = function(){
x.abort();
}
</script>
</body>
四、axios
1.axios的配置
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
2.get的基本使用
btn1.onclick = function(){
axios({
method:'GET',
url:'http://localhost:3000/posts/2'
}).then(response => {
console.log(response);
});
};
3.post的基本使用
btn2.onclick = function(){
axios({
method:'POST',
url:'http://localhost:3000/posts',
data:{
id:3,
title:'The weather is comfortable today!',
author:'mting'
}
}).then(response => {
console.log(response);
});
};
4.更新数据
btn3.onclick = function(){
axios({
method:'PUT',
url:'http://localhost:3000/posts/3',
data:{
id:3,
title:'The weather is comfortable today!',
author:'professor'
}
}).then(response => {
console.log(response);
});
};
5. 其他使用方法
btns[0].onclick = function(){
axios.request({
method:'GET',
url:'http://localhost:3000/comments'
}).then(response =>{
console.log(response);
})
};
btns[1].onclick = function(){
axios.post(
'http://localhost:3000/comments',
{
'body':'喜大普奔',
'postId':2
}).then(response =>{
console.log(response);
})
}
6.axios默认配置
<script>
const btns = document.querySelectorAll('button');
axios.defaults.method = 'GET';
axios.defaults.baseURL = 'http://localhost:3000';
btns[0].onclick = function(){
axios({
url:'/posts'
}).then(response =>{
console.log(response);
})
}
</script>
7.请求取消
<body>
<button>发送请求</button>
<button>取消请求</button>
<script>
const btns = document.querySelectorAll('button');
let cancel = null;
btns[0].onclick = function(){
if(cancel !==null){
cancel();
}
axios({
method:'GET',
url:'http://localhost:3000/posts',
cancelToken: new axios.CancelToken(function(c) {
// 将c的值赋值给cancel
cancel = c;
})
}).then(response=>{
console.log(response);
cancel = null;
})
};
btns[1].onclick = function(){
cancel();
}
</script>
</body>
五、跨域
1.Ajax同源策略
同源策略是浏览器的一种安全策略,违背同源策略就是跨域
同源:协议,域名,端口号必需完全相同
其他问题:ajax中在控制台输入nodemon server.js报错
解决方法:在控制台输入npx nodemon server.js
axios使用文档:axios中文文档|axios中文网 | axios
json-server使用文档:GitHub - typicode/json-server: Get a full fake REST API with zero coding in less than 30 seconds (seriously)
本文深入探讨Ajax的特点,包括其无需刷新页面通信和更新部分页面内容的能力,同时指出其跨域和SEO的挑战。详细讲解了HTTP协议的请求报文和响应报文结构,并通过实例展示了原生Ajax的get和post请求,以及处理超时、取消请求的方法。此外,还介绍了axios库的使用,包括get、post操作和配置,并涉及跨域问题。
411

被折叠的 条评论
为什么被折叠?



