抱歉,您的浏览器无法访问本站

本页面需要浏览器支持(启用)JavaScript


了解详情 >

Mr.wang

Time flies and people come and go

AJAX 的基本请求方式

AJAX

一种异步数据交互技术

解决的问题: 提高用户的体验

现在开发里面,使用 ajax 实现前后端的完全分离开发

ajax 使用的四个步骤

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 1 创建异步对象
var xhr = new XMLHttpRequest();
// 2 指定请求的方式和请求的地址
xhr.open(请求方式, 目标地址);
// 3 发送请求
xhr.send();
// 4 注册状态变化的监听(事件)
xhr.onreadystatechange = function () {
// 关注最终的结果
if (xhr.readyState == 4 && xhr.status == 200) {
//把响应体获取
console.log(xhr.responseText);
}
};

异步对象的 readyState 属性,是一个从 0-4 不断变化的数字,每个数字代表一个状态,我们只需要大概了解一下,关心最终的结果就可以了

fetch

基本用法

get

1
fetch(url).then(res=>res.json()).then(data=>console.log(data))

配置Fetch请求

1
2
3
4
5
6
7
8
9
10
11
12
13
fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include(含cookie), *same-origin, omit
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify(data) // body data type must match "Content-Type" header
});

备注: 当请求使用 credentials: ‘include’ 时,响应的 Access-Control-Allow-Origin 不能使用通配符 “*”。在这种情况下,Access-Control-Allow-Origin 必须是当前请求的源,在使用 CORS Unblock 插件的情况下请求仍会失败。

评论