传统的xhr请求写起来非常的混乱,但是使用fetch之后,如下所示:这种链式调用的风格看上去会非常舒服。
1.fetch发送get请求:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body>
<script>
// get
fetch(
"https://api.apiopen.top/getSingleJoke?sid=28654780"
).then((res) => {
// res拿到的是响应报文,需要解析
return res.json();
// 返回数据是json字符串,就可以解析成json格式
// res.json返回的是一个promise对象
// 就可以解析成字符串格式
// res.text返回的是一个promise对象
}).then((data) => {
// data就是解析成功的格式数据
console.log(data);
});
</script>
</html>
2.fetch发送post请求:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body>
<script>
fetch("https://api.apiopen.top/getSingleJoke", {
method: "POST",
headers: { // 设置请求头
"content-type": "application/x-www-form-urlencoded",
},
body: `sid = 28654780`,
}).then((res) => {
// 解析:
return res.json();
}).then((data) => {
console.log(data);
});
</script>
</html>
当然,fetch方法还能搭配vue一起使用