目录
2. XMLHttpRequest的state ( 状态 )
02 - POST 请求 x-www-form-urlencoded 格式
03 - POST 请求 FormData 格式 ( 默认格式 )
02 - POST 请求 x-www-form-urlencoded 格式
03 - POST 请求 FormData 格式 ( 默认格式 )
一、发展历程
1. 服务器端渲染
服务器端渲染(SSR,server side render): 早期的网页都是通过后端渲染来完成的
- 客户端发出请求
- 服务端接收请求并返回相应HTML文档
- 页面刷新,客户端加载新的HTML文档
缺点 :
- 当用户点击页面中的某个按钮向服务器发送请求时,页面本质上只是一些数据发生了变化,而此时服务器却要将重绘的整个页面再返回给浏览器加载,这显然有悖于程序员的“DRY( Don‘t repeat yourself )”原则
- 而且明明只是一些数据的变化却迫使服务器要返回整个HTML文档,这本身也会给网络带宽带来不必要的开销
2. 前后端分离
前端只需要独立编写客户端代码,后端也只需要独立编写服务端代码提供数据接口
前端通过AJAX请求来访问后端的数据接口,将Model展示到View中即可
AJAX : 是“Asynchronous JavaScript And XML”的缩写(异步的JavaScript和XML),是一种实现 无页面刷新 获取服务器数据的技术
- AJAX最吸引人的就是它的“异步”特性,也就是说它可以在不重新刷新页面的情况下与服务器通信,交换数据,或更新页面
- 只向服务器请求新的数据,并且在阻止页面刷新的情况下,动态的替换页面中展示的数据
二、HTTP
1. 概念
HTTP :
- 超文本传输协议(英语:HyperText Transfer Protocol,缩写:HTTP)是一种用于分布式、协作式和超媒体信息系统的应用层协议
- HTTP是万维网的数据通信的基础,设计HTTP最初的目的是为了提供一种发布和接收HTML页面的方法
- 通过HTTP或者HTTPS协议请求的资源由统一资源标识符(Uniform Resource Identifiers,URI)来标识
HTTP是一个客户端(用户)和服务端(网站)之间请求和响应的标准 :
- 通过使用网页浏览器、网络爬虫或者其它的工具,客户端发起一个HTTP请求到服务器上指定端口(默认端口为80)
- 称这个客户端为用户代理程序(user agent)
- 响应的服务器上存储着一些资源,比如HTML文件和图像
- 称这个响应服务器为源服务器(origin server)
2. 网页中资源的获取
网页中的资源通常是被放在Web资源服务器中,由浏览器自动发送HTTP请求来获取、解析、展示
页面中很多数据是动态展示的 :
- 比如页面中的数据展示、搜索数据、表单验证等等,也是通过在JavaScript中发送HTTP请求获取的
3. HTTP的组成
一次HTTP请求主要包括:请求(Request)和响应(Response)
01 - 请求
02 - 响应
4. HTTP的版本
- HTTP/0.9
- 发布于1991年
- 只支持GET请求方法获取文本数据,当时主要是为了获取HTML页面内容
- HTTP/1.0
- 发布于1996年
- 支持POST、HEAD等请求方法,支持请求头、响应头等,支持更多种数据类型(不再局限于文本数据)
- 但是浏览器的每次请求都需要与服务器建立一个TCP连接,请求处理完成后立即断开TCP连接,每次建立连接增加了性能损耗
- HTTP/1.1(目前使用最广泛的版本)
- 发布于1997年
- 增加了PUT、DELETE等请求方法
- 采用持久连接(Connection: keep-alive),多个请求可以共用同一个TCP连接
- 2015年,HTTP/2.0
- 2018年,HTTP/3.0
5. HTTP的请求方式
在RFC中定义了一组请求方式,来表示要对给定资源执行的操作 :
- GET:GET 方法请求一个指定资源的表示形式,使用 GET 的请求应该只被用于获取数据。
- HEAD:HEAD 方法请求一个与 GET 请求的响应相同的响应,但没有响应体
- 比如在准备下载一个文件前,先获取文件的大小,再决定是否进行下载
- POST:POST 方法用于将实体提交到指定的资源
- PUT:PUT 方法用请求有效载荷(payload)替换目标资源的所有当前表示
- DELETE:DELETE 方法删除指定的资源
- PATCH:PATCH 方法用于对资源应部分修改
- CONNECT:CONNECT 方法建立一个到目标资源标识的服务器的隧道,通常用在代理服务器,网页开发很少用到
- TRACE:TRACE 方法沿着到目标资源的路径执行一个消息环回测试
开发中使用最多的是GET、POST请求
6. HTTP Request Header
01 - content - type
content - type : 是这次请求携带的数据的类型
- application/x-www-form-urlencoded :表示数据被编码成以 '&' 分隔的键 - 值对,同时以 '=' 分隔键和值
- application/json:表示是一个json类型
- text/plain:表示是文本类型
- application/xml:表示是xml类型
- multipart/form-data:表示是上传文件
02 - content-length
content-length:文件的大小长度
03 - keep-alive
- http是基于TCP协议的,但是通常在进行一次请求和响应结束后会立刻中断
- 在http1.0中,如果想要继续保持连接
- 浏览器需要在请求头中添加 connection: keep-alive
- 服务器需要在响应头中添加 connection:keey-alive
- 当客户端再次放请求时,就会使用同一个连接,直接一方中断连接
- 在http1.1中,所有连接默认是 connection: keep-alive的
- 不同的Web服务器会有不同的保持 keep-alive的时间
- Node中默认是5s中
04 - accept-encoding
告知服务器,客户端支持的文件压缩格式,比如js文件可以使用gzip编码,对应 .gz文件
主要用于请求文件 : 如果支持gzip压缩格式,则会请求该文件,浏览器会自动解压并解析
05 - accept
告知服务器,客户端可接受文件的格式类型
主要用于请求数据,例如 : 是否支持json、xml的数据类型,如果支持即可返回
06 - user-agent
客户端相关的信息
7. HTTP Response响应状态码
Http状态码(Http Status Code)是用来表示Http响应状态的数字代码 :
- Http状态码非常多,可以根据不同的情况,给客户端返回不同的状态码
- MDN响应码解析地址 : HTTP 响应状态码 - HTTP | MDN
8. HTTP Response Header
一般并不常用
三、AJAX
AJAX 是异步的 JavaScript 和 XML(Asynchronous JavaScript And XML)
它可以使用 JSON,XML,HTML 和 text 文本等格式发送和接收数据
1. 发送请求
- 第一步:创建网络请求的AJAX对象(使用XMLHttpRequest)
- 第二步:监听XMLHttpRequest对象状态的变化,或者监听onload事件(请求完成时触发)
- 第三步:配置网络请求(通过open方法)
- 第四步:发送send网络请求
// 1.创建XMLHttpRequest对象
const xhr = new XMLHttpRequest();
// 2.监听状态的改变(宏任务)
// 会自动监听4种状态,也就是会调用4次
xhr.onreadystatechange = function () {
// 如果不是下载完数据,就直接返回
if (xhr.readyState !== XMLHttpRequest.DONE) return;
// if (xhr.readyState !== 4) return;
// 默认拿到的是字符串对象
// 将字符串转成JSON对象(js对象)
console.log(JSON.parse(xhr.response));
};
// 3.配置请求open
// method: 请求的方式(get/post/delete/put/patch...)
// url: 请求的地址
xhr.open('get', 'http://www.baidu.com/nice');
// 4.发送请求(浏览器帮助发送对应请求)
xhr.send();
2. XMLHttpRequest的state ( 状态 )
在一次网络请求中状态发生了很多次变化,这是因为对于一次请求来说包括如下的状态
3. 发送同步请求
const xhr = new XMLHttpRequest();
// xhr.onreadystatechange = function () {
// if (xhr.readyState !== XMLHttpRequest.DONE) return;
// console.log(JSON.parse(xhr.response));
// };
// 将 open 的第三个参数设置为 false,即为同步请求
xhr.open('get', 'http://www.baidu.com/nice', false);
xhr.send();
console.log(JSON.parse(xhr.response));
console.log('-----等请求到数据后,方能执行到这');
4. XMLHttpRequest 其他事件监听
除了onreadystatechange还有其他的事件可以监听
- loadstart : 请求开始
- progress : 一个响应数据包到达,此时整个 response body 都在 response 中
- abort : 调用 xhr.abort() 取消了请求
- error : 发生连接错误,例如,域错误。不会发生诸如 404 这类的 HTTP 错误
- load : 请求成功完成
- timeout : 由于请求超时而取消了该请求(仅发生在设置了 timeout 的情况下)
- loadend : 在 load,error,timeout 或 abort 之后触发
const xhr = new XMLHttpRequest();
// 请求成功完成的监听,也可拿到数据,而且不用判断
xhr.onload = function () {
console.log(JSON.parse(xhr.response));
};
xhr.open('get', 'http://www.baidu.com/nice');
xhr.send();
5. 响应数据和响应类型
发送了请求后,需要获取对应的结果:response属性
- XMLHttpRequest response 属性返回响应的正文内容;
- 返回的类型取决于responseType的属性设置
通过responseType可以设置获取数据的类型
将 responseType 的值设置为空字符串,则会使用 text 作为默认值
也就是说,默认就是text格式的数据
01 - text 类型
// 1. 创建对象
const xhr = new XMLHttpRequest();
// 2. 监听请求成功
xhr.onload = function () {
console.log(xhr.response);
// 如果是text类型的数据,也可以这么获得
console.log(xhr.responseText);
};
// 3. 配置响应类型
xhr.responseType = ''; // 默认其实为text => xhr.responseType = 'text'
// 4. 配置请求参数
xhr.open('get', 'http://www.baidu.com/nice');
// 5. 发送请求
xhr.send();
02 - json 类型
// 1. 创建对象
const xhr = new XMLHttpRequest();
// 2. 监听请求成功
xhr.onload = function () {
console.log(xhr.response);
};
// 3. 配置响应类型为 => json格式
xhr.responseType = 'json';
// 4. 配置请求参数
xhr.open('get', 'http://www.baidu.com/nice');
// 5. 发送请求
xhr.send();
03 - xml 类型
// 1. 创建对象
const xhr = new XMLHttpRequest();
// 2. 监听请求成功
xhr.onload = function () {
console.log(xhr.response);
// 如果是xml类型的数据,也可以这么获得
console.log(xhr.responseXML);
};
// 3. 配置响应类型为 => xml格式
xhr.responseType = 'xml';
// 4. 配置请求参数
xhr.open('get', 'http://www.baidu.com/nice');
// 5. 发送请求
xhr.send();
6. HTTP响应的状态 status
如果希望获取HTTP响应的网络状态,可以通过status和statusText来获取
// 1.创建对象
const xhr = new XMLHttpRequest();
// 2.监听结果
xhr.onload = function () {
console.log(xhr.status, xhr.statusText);
// 根据http的状态码判断是否请求成功
if (xhr.status >= 200 && xhr.status < 300) {
console.log(xhr.response);
} else {
// 注 : 404 的时候来的是这个位置
console.log(xhr.status, xhr.statusText);
}
};
// 请求未发送成功,没有发送到服务器的回调
xhr.onerror = function () {
console.log('onerror', xhr.status, xhr.statusText);
};
// 3.设置响应类型
xhr.responseType = 'json';
// 4.配置网络请求
xhr.open('get', 'http://www.baidu.com/nice');
// 5.发送网络请求
xhr.send();
7. GET / POST 请求传递参数
01 - GET 请求的 query 参数
// 1. 创建对象
const xhr = new XMLHttpRequest();
// 2. 监听请求成功
xhr.onload = function () {};
// 3. 配置数据响应类型为 => xml格式
xhr.responseType = 'json';
// 4. 配置请求参数
/**
* get请求 : 这么传参数
*/
xhr.open('get', 'http://www.baidu.com/nice?name=star&age=18');
// 5. 发送请求
xhr.send();
02 - POST 请求 x-www-form-urlencoded 格式
// 1. 创建对象
const xhr = new XMLHttpRequest();
// 2. 监听请求成功
xhr.onload = function () {};
// 3. 配置数据响应类型为 => xml格式
xhr.responseType = 'json';
// 4. 配置请求参数
/**
* post请求 : x-www-form-urlencoded 格式
*/
xhr.open('post', 'http://www.baidu.com/nice');
// 在请求头中配置格式
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
// 5. 发送请求,参数写在这里
xhr.send('name=star&age=18');
03 - POST 请求 FormData 格式 ( 默认格式 )
<form class="form">
<!-- 记得加上name属性,否则传递不过去数据 -->
<input type="text" name="username" />
<input type="password" name="password" />
</form>
<button class="btn">提交</button>
<script>
const formDom = document.querySelector('.form');
const btnDom = document.querySelector('.btn');
btnDom.onclick = function () {
// 1. 创建对象
const xhr = new XMLHttpRequest();
// 2. 监听请求成功
xhr.onload = function () {};
// 3. 配置数据响应类型为 => xml格式
xhr.responseType = 'json';
// 4. 配置请求参数
/**
* post请求 : FormData 格式,默认格式,所以不需要配置
* 1. 表单提交,需加上name属性
* 2. 提交的数据需转换为FormData格式
*/
xhr.open('post', 'http://www.baidu.com/nice');
// formDom对象转成FormData对象
const formData = new FormData(formDom);
// 5. 发送请求,参数写在这里
xhr.send(formData);
};
04 - POST 请求 JSON 格式
// 1. 创建对象
const xhr = new XMLHttpRequest();
// 2. 监听请求成功
xhr.onload = function () {};
// 3. 配置数据响应类型为 => xml格式
xhr.responseType = 'json';
// 4. 配置请求参数
/**
* post请求 : json 格式
*/
xhr.open('post', 'http://www.baidu.com/nice');
// 在请求头中配置格式
xhr.setRequestHeader('Content-type', 'application/json');
// 5. 发送请求,参数写在这里
// 注 : 这里仍然要传字符串,不过格式要为json的字符串格式
xhr.send(JSON.stringify({ name: 'star', age: 18 }));
8. 延迟时间timeout和取消请求
<body>
<button>取消请求</button>
<script>
const xhr = new XMLHttpRequest();
xhr.onload = function () {
console.log(xhr.response);
};
xhr.onabort = function () {
console.log('请求被取消掉了');
};
xhr.responseType = 'json';
// 1.超时时间的设置
xhr.ontimeout = function () {
console.log('请求过期: timeout');
};
// timeout: 浏览器达到过期时间还没有获取到对应的结果时, 取消本次请求
// xhr.timeout = 3000
xhr.open('get', 'http://www.baidu.com/nice');
xhr.send();
// 2.手动取消结果
const cancelBtn = document.querySelector('button');
cancelBtn.onclick = function () {
// 取消请求
xhr.abort();
};
</script>
</body>
9. Ajax 网络请求封装
01 - 回调函数
function hyajax({
url,
method = "get",
data = {},
timeout = 10000,
headers = {}, // token
success,
failure
} = {}) {
// 1.创建对象
const xhr = new XMLHttpRequest()
// 2.监听数据
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 300) {
success && success(xhr.response)
} else {
failure && failure({ status: xhr.status, message: xhr.statusText })
}
}
// 3.设置类型
xhr.responseType = "json"
xhr.timeout = timeout
// 4.open方法
if (method.toUpperCase() === "GET") {
const queryStrings = []
for (const key in data) {
queryStrings.push(`${key}=${data[key]}`)
}
url = url + "?" + queryStrings.join("&")
xhr.open(method, url)
xhr.send()
} else {
xhr.open(method, url)
xhr.setRequestHeader("Content-type", "application/json")
xhr.send(JSON.stringify(data))
}
return xhr
}
02 - promise
function hyajax({
url,
method = "get",
data = {},
timeout = 10000,
headers = {}, // token
} = {}) {
// 1.创建对象
const xhr = new XMLHttpRequest()
// 2.创建Promise
const promise = new Promise((resolve, reject) => {
// 2.监听数据
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr.response)
} else {
reject({ status: xhr.status, message: xhr.statusText })
}
}
// 3.设置类型
xhr.responseType = "json"
xhr.timeout = timeout
// 4.open方法
if (method.toUpperCase() === "GET") {
const queryStrings = []
for (const key in data) {
queryStrings.push(`${key}=${data[key]}`)
}
url = url + "?" + queryStrings.join("&")
xhr.open(method, url)
xhr.send()
} else {
xhr.open(method, url)
xhr.setRequestHeader("Content-type", "application/json")
xhr.send(JSON.stringify(data))
}
})
promise.xhr = xhr
return promise
}
四、Fetch
1. 概念
Fetch可以看做是早期的XMLHttpRequest的替代方案,它提供了一种更加现代的处理方案
- 返回值是一个Promise,提供了一种更加优雅的处理结果方式
- 在请求发送成功时,调用resolve回调then
- 在请求发送失败时,调用reject回调catch
- 不像XMLHttpRequest一样,所有的操作都在一个对象上
2. 使用
- input:定义要获取的资源地址
- 可以是一个URL字符串
- 也可以使用一个Request对象(实验性特性)类型
- init:其他初始化参数
- method: 请求使用的方法,如 GET、POST; ✓ headers: 请求的头信息
- body: 请求的 body 信息
01 - 基本使用
/**
* fetch是全局函数,直接使用即可
* 默认发送的是get请求,数据格式是formData格式
*/
fetch('http://www.baidu.com/nice')
.then((res) => {
// 1. 拿到的是数据流,并不是真正的结果
const reponse = res;
// 2. reponse.json()返回的也是 promise 对象
reponse.json().then((res) => {
// 2.拿到真正的数据
console.log(res);
});
})
.catch((err) => {
console.log(err);
});
02 - 优化方式一
/**
* fetch是全局函数,直接使用即可
* 默认发送的是get请求,数据格式是formData格式
*/
fetch('http://www.baidu.com/nice')
.then((res) => {
// 1. 拿到的是数据流,并不是真正的结果
const reponse = res;
// 2.返回出去
return reponse.json();
})
.then((res) => {
// 3.拿到真正的数据
console.log(res);
})
.catch((err) => {
console.log(err);
});
03 - 优化方式二
/**
* fetch是全局函数,直接使用即可
* 默认发送的是get请求,数据格式是formData格式
*/
async function getData() {
// 1. 拿到数据流
const reponse = await fetch('http://www.baidu.com/nice');
// 2. 拿到真正数据
const res = await reponse.json();
console.log(res);
}
getData();
3. Fetch数据的响应
Fetch的数据响应主要分为两个阶段 :
- 阶段一:当服务器返回了响应(response)
- fetch 返回的 promise 就使用内建的 Response class 对象来对响应头进行解析
- 在这个阶段,我们可以通过检查响应头,来检查 HTTP 状态以确定请求是否成功
- 如果 fetch 无法建立一个 HTTP 请求,例如网络问题,亦或是请求的网址不存在,那么 promise 就会 reject
- 异常的 HTTP 状态,例如 404 或 500,不会导致出现 error
- 可以在 response 的属性中看到 HTTP 状态
- status:HTTP 状态码,例如 200
- ok:布尔值,如果 HTTP 状态码为 200-299,则为 true
- 第二阶段,为了获取 response body,需要使用一个其他的方法调用
- response.text ( ) —— 读取 response,并以文本形式返回 response
- response.json ( ) —— 将 response 解析为 JSON
4. 发送请求
01 - GET 请求的 query 参数
/**
* fetch是全局函数,直接使用即可
* 默认发送的是get请求,数据格式是formData格式
*/
async function getData(params) {
// 1. 拿到数据流
const reponse = await fetch(`http://www.baidu.com/nice/get?${params}`);
// 2. 拿到真正数据
const res = await reponse.json();
console.log(res);
}
getData('name=123&age=18');
02 - POST 请求 x-www-form-urlencoded 格式
async function getData() {
// 1. 拿到数据流
const reponse = await fetch('http://www.baidu.com/nice', {
method: 'post',
headers: {
'Content-type': 'application/x-www-form-urlencoded'
},
body: 'name=coder&age=18'
});
// 2. 拿到真正数据
const res = await reponse.json();
console.log(res);
}
getData();
03 - POST 请求 FormData 格式 ( 默认格式 )
async function getData() {
const formData = new FormData();
formData.append('name', 'star');
formData.append('age', '19');
// 1. 拿到数据流
const reponse = await fetch('http://www.baidu.com/nice', {
method: 'post',
body: formData
});
// 2. 拿到真正数据
const res = await reponse.json();
console.log(res);
}
getData();
04 - POST 请求 JSON 格式
async function getData() {
// 1. 拿到数据流
const reponse = await fetch('http://www.baidu.com/nice', {
method: 'post',
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify({
name: 'star',
age: 18
})
});
// 获取response状态
console.log(reponse.ok, reponse.status, reponse.statusText); // true 200 'OK'
// 2. 拿到真正数据
const res = await reponse.json();
console.log(res);
}
getData();
五、上传文件
1. XHR 上传
<input class="file" type="file" />
<button class="upload">上传文件</button>
<script>
const uploadBtn = document.querySelector('.upload');
// 1. 点击上传
uploadBtn.onclick = function () {
// 2. 创建对象
const xhr = new XMLHttpRequest();
// 3. 监听结果
xhr.onload = function () {
console.log(xhr.response);
};
// 4. 可以监听到请求的过程
xhr.onprogress = function (event) {
console.log(event);
};
xhr.responseType = 'json';
// 5. 设置请求参数
xhr.open('post', 'http://www.baidu.com/nice');
const fileEl = document.querySelector('.file');
// 拿到上传的文件对象
const file = fileEl.files[0];
// 上传文件基本都是表单提交
const formData = new FormData();
formData.append('avatar', file);
// 6. 发送请求
xhr.send(formData);
};
</script>
2. Fetch 上传
<input class="file" type="file" />
<button class="upload">上传文件</button>
<script>
const uploadBtn = document.querySelector('.upload');
uploadBtn.onclick = async function () {
// 表单
const fileEl = document.querySelector('.file');
const file = fileEl.files[0];
const formData = new FormData();
formData.append('avatar', file);
// 发送fetch请求
const response = await fetch('http://www.baidu.com/nice', {
method: 'post',
body: formData
});
const res = await response.json();
console.log('res:', res);
};
</script>