Fetch异步请求

fetch是一种可代替 ajax 获取/提交数据的技术

fetch的参数

(一)url信息(即请求的处理路径)
(二)第二个是初始化信息,包括以下几种:

  1. method:请求方法,常用的有get和post;
  2. headers:请求头信息,最常用的就是表单格式的数据:”Content-type”:”application/x-www-form-urlencoded”;是一个对象
  3. body:要发送到后台的参数,可以为ArrayBuffer,String,FormData等类型

从上面的代码我们可以知道fetch()方法返回的是一个promise对象

get 和post请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//get
fetch('/get?name=chaoxue')
.then(e=>e.json())
.then((data)=>{
console.log(data);
});


//post
fetch('/post',{
method:'POST',
headers : { // 请求头
'Content-Type': 'application/x-www-form-urlencoded'
},
body:new URLSearchParams({"name": "chaoxue"},{"pass": 2}).toString()
})
.then(e=>e.json())
.then((data)=>{
console.log(data);
});
请我吃辣条吧~~
-------------本文结束感谢您的阅读-------------