Ajax
1.发送异步请求,无刷新获取数据,实现懒加载。
2.服务器端通常接收如下三种数据格式
-xml
- json
- html
可以通过ajax请求传输
Ajax前置知识
1.http超文本传输协议
a.请求报文格式与参数
-行 GET /s?id=utf-8 HTTP/1.1
-头 参数
-空行
-体
……
b.响应报文
-行 GET 200 OK HTTP/1.1
-头 参数
-空行
-体
……
注解:可以观察浏览器network处的请求
Ajax发送请求XMLHttpRequest
1.GET
<script>
const btn = document.getElementById("liyong");
btn.onclick = function() {
const xhr = new XMLHttpRequest();
// 初始化请求
// xhr.open("GET","http://localhost:8080/hello?name=liyong");
xhr.open("GET","http://localhost:8080/hello");
// 返送请求
xhr.send();
// 事件绑定,处理返回结果
// readState 是xhr中对象的属性,表示状态0,1,2,3,4
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if(xhr.status >= 200 && xhr.status < 300) {
console.log("成功!");
}
}
}
}
</script>
2.Post
<script>
const btn = document.getElementById("liyong");
btn.onclick = function() {
const xhr = new XMLHttpRequest();
// 初始化请求
xhr.open("POST","http://localhost:8080/hello");
// 返送请求
xhr.send();
xhr.send("a=100&b=200");
xhr.send("a:100&b:200");
xhr.send("{}");
// 事件绑定,处理返回结果
// readState 是xhr中对象的属性,表示状态0,1,2,3,4
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if(xhr.status >= 200 && xhr.status < 300) {
btn.innerHTML = xhr.response;
}
}
}
}
</script>
3.设置请求头
xhr.setRequestHeader("Content-Type","xxx");
4.josn的响应与处理
// 自动转换
xhr.responseType = "json";
xhr.setRequestHeader("Content-Type","xxx");
// 事件绑定,处理返回结果
// readState 是xhr中对象的属性,表示状态0,1,2,3,4
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if(xhr.status >= 200 && xhr.status < 300) {
let data = {};
// 手动转换JOSN
data = JSON.parse(xhr.response);
console.log(data.name);
}
}
}
5.IE浏览器缓存
IE会缓存Ajax的请求,利用时间戳
xhr.open("GET","http://localhost:8080/hello?t=" + Date.now());
6.设置超时
xhr.responseType = "json";
// 设置超时时间
xhr.timeout = 2000;
// 设置超时回调
xhr.ontimeout = function() {
console.log("请求超时!");
}
7.网络异常回调
xhr.onerror = function() {
console.log("网络异常!");
}
8.取消请求
xhr.abort(); //取消请求
9.重复请求
<script>
const btn = document.getElementById("liyong");
// 判断标志
let isSending = false;
let xhr = null;
btn.onclick = function() {
xhr = new XMLHttpRequest();
// 存在正在发送的相同请求取消
if (isSending == true) xhr.abort();
// 初始化请求
xhr.open("POST","http://localhost:8080/hello");
// 返送请求
xhr.send();
// 标志请求是否正在发送
xhr.setRequestHeader("Content-Type","xxx");
// 事件绑定,处理返回结果
xhr.onreadystatechange = function() {
isSending = true;
if (xhr.readyState == 4) {
// 请求完成变为false
isSending = false;
if(xhr.status >= 200 && xhr.status < 300) {
}
}
}
}
</script>
Jquery中的Ajax
1.get
<body>
<button id = "get"><p>get</p></div>
<button id ="post"><p>post</p></div>
<button id ="common"><p>common</p></div>
</body>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
<script>
$("button").eq(0).click(function() {
// 地址 参数 回调
alert("yes");
$.get("http://localhost:8080/hello1",{a:100,b:200},function () {
console.log("成功!");
});
})
</script>
2.post
$("button").eq(1).click(function() {
// 地址 参数 回调 数据类型
alert("yes");
$.post("http://localhost:8080/hello",{a:100,b:200},function () {
console.log("成功!");
},"json");
})
3.通用ajax
$.ajax({
// 地址
url : "http://localhost:8080/hello",
// 参数
data : {a:100},
// 响应数据格式
dataType : "json",
type : "GET",
// 成功
success : function() {
console.log("成功!");
},
// 超时时间
timeout : 2000,
// 失败
error : function() {
console.log("失败!");
},
// 请求头
headers :{
liyong : "成功!"
}
});
axios发送Ajax请求
1.axios
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.0/axios.js"></script>
<script>
// 简化URL
axios.baseURL ="";
const btns = document.querySelectorAll("button");
btns[0].onclick = function () {
// GET
axios.get("http://localhost:8080/hello1",{
// url参数
params : {
id : 100,
vip : 7
},
headers:{
name:'liyong',
age : 20
}
// 处理响应
}).then();
}
</script>
// post
axios.get("http://localhost:8080/hello1",{
// url参数
params : {
id : 100,
vip : 7
},
headers:{
name:'liyong',
age : 20
},
data : {
name : "liyong",
age : 20
}
// 处理响应
}).then();
2.axios函数
// Send a POST request
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
// GET request for remote image in node.js
axios({
method: 'get',
url: 'http://bit.ly/2mTM3nY',
responseType: 'stream'
})
.then(function (response) {
response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
});
fetch发送请求
fetch('https://www.easy-mock.com/mock/5f507e38a758c95f67d6eb42/fetch/postmsg',{
method:'POST',
body:data
})
.then(response => response.json())
.then(data => console.log(data));
资源问题
1.协议,域名,端口号必须完全相同
2.违背同源策略就是跨域
3.解决跨域
a.jsonp只支持get请求
jsonp返回一个可以执行的javascript串
b.CORS文档地址
https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS#HTTP_%E5%93%8D%E5%BA%94%E9%A6%96%E9%83%A8%E5%AD%97%E6%AE%B5