
目录
2. XMLHttpRequest的state ( 状态 )
02 - POST 请求 x-www-form-urlencoded 格式
03 - POST 请求 FormData 格式 ( 默认格式 )
02 - POST 请求 x-www-form-urlencoded 格式
03 - POST 请求 FormData 格式 ( 默认格式 )
服务器端渲染(SSR,server side render): 早期的网页都是通过后端渲染来完成的
缺点 :

前端只需要独立编写客户端代码,后端也只需要独立编写服务端代码提供数据接口
前端通过AJAX请求来访问后端的数据接口,将Model展示到View中即可
AJAX : 是“Asynchronous JavaScript And XML”的缩写(异步的JavaScript和XML),是一种实现 无页面刷新 获取服务器数据的技术

HTTP :
HTTP是一个客户端(用户)和服务端(网站)之间请求和响应的标准 :

网页中的资源通常是被放在Web资源服务器中,由浏览器自动发送HTTP请求来获取、解析、展示

页面中很多数据是动态展示的 :
一次HTTP请求主要包括:请求(Request)和响应(Response)



在RFC中定义了一组请求方式,来表示要对给定资源执行的操作 :
开发中使用最多的是GET、POST请求

content - type : 是这次请求携带的数据的类型
content-length:文件的大小长度
告知服务器,客户端支持的文件压缩格式,比如js文件可以使用gzip编码,对应 .gz文件
主要用于请求文件 : 如果支持gzip压缩格式,则会请求该文件,浏览器会自动解压并解析
告知服务器,客户端可接受文件的格式类型
主要用于请求数据,例如 : 是否支持json、xml的数据类型,如果支持即可返回
客户端相关的信息
Http状态码(Http Status Code)是用来表示Http响应状态的数字代码 :

一般并不常用

AJAX 是异步的 JavaScript 和 XML(Asynchronous JavaScript And XML)
它可以使用 JSON,XML,HTML 和 text 文本等格式发送和接收数据
- // 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();
在一次网络请求中状态发生了很多次变化,这是因为对于一次请求来说包括如下的状态

- 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('-----等请求到数据后,方能执行到这');
除了onreadystatechange还有其他的事件可以监听
- const xhr = new XMLHttpRequest();
- // 请求成功完成的监听,也可拿到数据,而且不用判断
- xhr.onload = function () {
- console.log(JSON.parse(xhr.response));
- };
- xhr.open('get', 'http://www.baidu.com/nice');
- xhr.send();
发送了请求后,需要获取对应的结果:response属性
通过responseType可以设置获取数据的类型
将 responseType 的值设置为空字符串,则会使用 text 作为默认值
也就是说,默认就是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();
- // 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();
- // 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();
如果希望获取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();
- // 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();
- // 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');
-
- <input type="text" name="username" />
- <input type="password" name="password" />
- <button class="btn">提交button>
- 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);
- };
- // 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 }));
- <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>
- 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
- }
- 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可以看做是早期的XMLHttpRequest的替代方案,它提供了一种更加现代的处理方案

- /**
- * 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);
- });
- /**
- * 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);
- });
- /**
- * 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();
Fetch的数据响应主要分为两个阶段 :
- /**
- * 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');
- 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();
- 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();
- 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();
- 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>
- 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>