在维基百科中的解释
HTTP是客户端(用户)和服务端(网站)之间请求和响应的标准
content-type是这次请求携带的数据类型
content-length:文件的大小长度,不用手动配置
keep-alive
accept-encoding:告知服务器,客户端支持的压缩格式,服务器会返回相应的压缩格式的文件
**accept:**告知服务器,客户端可以接收的文件类型
**user-agent:**客户端的相关信息
AJAX是异步的JavaScript和XML
它可以使用JSON、XML、HTML和text文本等格式发送和接收数据
//创建AJAX对象
let xhr = new XMLHttpRequest();
//监听XMLHttpRequest对象状态的变化
xhr.onreadystatechange = function () {
console.log(xhr.response);
};
//配置网络请求
//method:get/post/delete
//URL
xhr.open("GET", "http://123.207.32.32:8000/home/multidata");
//发送send网络请求
xhr.send();
事实上,我们在一次网络请求中,可以看到XHR的状态发生了很多次的变化
值 | 状态 | 描述 |
---|---|---|
0 | UNSENT | 代理被创建,但是尚未调用open()方法(不会被监听) |
1 | OPENED | open()方法已经被调用 |
2 | HEADERS_RECEIVED | send()方法已经被调用,并且头部和状态已经可以获得 |
3 | LOADING | 下载中:reponseText属性已经包含部分数据 |
4 | DONE | 下载操作已经完成 |
//创建AJAX对象
let xhr = new XMLHttpRequest();
//监听XMLHttpRequest对象状态的变化
xhr.onreadystatechange = function () {
//这样写,代码阅读性不是很好
// if (xhr.readyState !== 4) return;
//此写法,等同于上面的的写法XMLHttpRequest.DONE代表常量
if (xhr.readyState !== XMLHttpRequest.DONE) return;
console.log(xhr.response);
};
//配置网络请求
//method:get/post/delete
//URL
xhr.open("GET", "http://123.207.32.32:8000/home/multidata");
//发送send网络请求
xhr.send();
XHR发送请求,默认发送的是异步请求,即不会阻塞xhr.send()后面代码的执行
xhr.send()
后面的代码xhr.open()
中传入第三个参数 false
//创建AJAX对象
let xhr = new XMLHttpRequest();
//监听XMLHttpRequest对象状态的变化
xhr.onreadystatechange = function () {
//这样写,代码阅读性不是很好
// if (xhr.readyState !== 4) return;
//此写法,等同于上面的的写法XMLHttpRequest.DONE代表常量
if (xhr.readyState !== XMLHttpRequest.DONE) return;
console.log(xhr.response);
};
//配置网络请求
//method:get/post/delete
//URL
xhr.open("GET", "http://123.207.32.32:8000/home/multidata",false);
//发送send网络请求
xhr.send();
//在这里即可拿到相应的数据
console.log(xhr.response)
除了
onreadystatechange
还有其他的事件可以监听
loadstart
:请求开始progress
:一个响应数据包到达,此时整个response body
都在 response
中abort
:调用 xhr.abort()
取消了请求error
:发生连接错误:域名解析错误或者跨域load
:请求完成//可以代替onreadystatechange进行数据的监听
xhr.onload = function () {
console.log(xhr.response);
};
timeout
:由于请求超时二取消了该请求(默认情况下是0,不会超时,手动设置后会有超时)loadend
:在load error timeout 或abort之后触发在发送网络请求,接收数据的时候,可以对数据的格式进行设置
xhr.responseType
进行设置text
格式//创建AJAX对象
//监听XMLHttpRequest对象状态的变化
//对响应数据格式进行设置
xhr.responseType = "json"
//配置网络请求
//发送send网络请求
通过
xhr.status
进行获取状态码,xhr.statusText
状态描述
//创建AJAX对象
let xhr = new XMLHttpRequest();
//监听XMLHttpRequest对象状态的变化
xhr.onreadystatechange = function () {
//这样写,代码阅读性不是很好
// if (xhr.readyState !== 4) return;
//此写法,等同于上面的的写法XMLHttpRequest.DONE代表常量
if (xhr.readyState !== XMLHttpRequest.DONE) return;
if (xhr.status >= 200 && xhr.status < 300) {
//返回正常数据
console.log(xhr.response);
} else {
//返回相应的错误信息
console.log(xhr.status, xhr.statusText);
}
};
//配置网络请求
//method:get/post/delete
//URL
xhr.open("GET", "http://123.207.32.32:8000/home/multidataa");
//发送send网络请求
xhr.send();
//创建AJAX对象
let xhr = new XMLHttpRequest();
//监听状态变化
xhr.onload = function () {
console.log(xhr.response);
};
//设置响应数据格式
xhr.responseType = "json";
//配置网络请求
//get请求,通过querystring进行参数的传递
xhr.open(
"get",
"http://123.207.32.32:1888/02_param/get?name=why&name=18&address=广州市"
);
//发送网络请求
xhr.send();
x-www-form-urlencoded
格式
xhr.setRequestHeader
//创建AJAX对象
let xhr = new XMLHttpRequest();
//监听状态变化
xhr.onload = function () {
console.log(xhr.response);
};
//post请求,发送urlencoded
xhr.open("post", "http://123.207.32.32:1888/02_param/posturl");
//告知发送的是什么格式的数据
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//发送网络请求
xhr.send("name=why&name=18&address=广州市");
FormData
格式
FormData
格式的数据,因此不用设置//HTML中有form表单,直接使用form表单即可
const formEl = document.getElementById("form")
//创建AJAX对象
let xhr = new XMLHttpRequest();
//监听状态变化
xhr.onload = function () {
console.log(xhr.response);
};
//post请求,发送formData数据
xhr.open("post", "http://123.207.32.32:1888/02_param/posturl");
const formData = new FormData(formEl)
//发送网络请求
xhr.send(formData);
JSON
格式:常用
//创建AJAX对象
let xhr = new XMLHttpRequest();
//监听状态变化
xhr.onload = function () {
console.log(xhr.response);
};
//设置响应数据格式
xhr.responseType = "json";
//post请求,发送JSON格式数据
xhr.open("post", "http://123.207.32.32:1888/02_param/postjson");
//告知服务器传递的JSON格式数据
xhr.setRequestHeader("Content-type", "application/json");
//发送网络请求,传递JSON字符串
xhr.send(JSON.stringify({ name: "why", age: 18, height: 1.88 }));
//创建AJAX对象
let xhr = new XMLHttpRequest();
//监听状态变化
xhr.onload = function () {
console.log(xhr.response);
};
//设置响应数据格式
xhr.responseType = "json";
//设置过期时间
xhr.timeout = 3000;
//监听过期时间
xhr.ontimeout = function () {
console.log("时间过期了");
};
//监听取消网络请求
xhr.onabort = function () {
console.log("网络请求被取消了");
};
//post请求,发送JSON格式数据
xhr.open("get", "http://123.207.32.32:1888/01_basic/timeout");
//发送网络请求,传递JSON字符串
xhr.send();
<input type="file" id="file" />
<button id="btn">上传button>
<script>
//获取元素
let file = document.getElementById("file");
let btn = document.getElementById("btn");
//绑定事件
btn.onclick = function () {
//获取上传的文件
let fileData = file.files;
//准备上传数据
let formData = new FormData();
formData.append("test", fileData[0]);
//实例化XHR对象
let xhr = new XMLHttpRequest();
//监听结果变化
xhr.onload = function () {
//获取结果
console.log(xhr.response);
};
//网络请求设置
xhr.open("POST", "123.207.32.32:1888/02_param/upload");
//发送网络请求
xhr.send(formData);
};
script>
可以看作是早期的XMLHttpRequest的替代方案
Fetch的返回值是一个promise
基本使用
//完成网络请求
fetch("http://123.207.32.32:8000/home/multidata").then((response) => {
console.log(response);
});
//获取具体数据(版本一)
fetch("http://123.207.32.32:8000/home/multidata").then((response) => {
//返回的数据是json就调用json(),text就调用text()方法
//该方法也是一个promise,使用.then获取具体内容
response.json().then((data) => {
console.log(data);
});
});
//以上版本的代码,在.then中调用了.then,因此可以进行以下优化
//通过链式调用的方式
fetch("http://123.207.32.32:8000/home/multidata")
.then((response) => {
//返回的数据是json就调用json(),text就调用text()方法
return response.json();
})
.then((data) => {
console.log(data);
});
//以上代码依旧可以做出优化,使用async/await
async function getData() {
let response = await fetch("http://123.207.32.32:8000/home/multidata");
let data = await response.json();
console.log(data);
}
getData();
response
中可以查看HTTP请求状态 console.log(response.status, response.ok, response.statusText);//200 true "OK"
使用post请求,默认传递的是formData格式的数据,因此传递其它格式的数据需要进行设置
async function getData() {
let response = await fetch("http://123.207.32.32:1888/02_param/postjson", {
//设置请求方法
method: "post",
//设置请求头
headers: {
"Content-type": "application/json",
},
//设置请求体
body: JSON.stringify({ a: 100 }),
});
let data = await response.json();
console.log(data);
}
getData();