自我学习记录(一直会更新🌺)未完待续。。。。
先来回答一个问题:除了Ajax获取后台数据之外,还有没有其他的替代方案?
答:fetch
request
fetch(input, init) // 这个方法接受两个参数:
| 参数 | 说明 |
|---|---|
| input | 定义要获取的资源。包含要获取资源的 url |
| init | 这个参数是可选的,它传入一个配置项对象,可以用它来包括所对请求进行设置 |
配置如下:
- method: 请求使用的方法,如 GET、POST。
- headers: 请求的头信息,形式为 Headers 对象或 ByteString。
| 参数 | 说明(指定提交方式) |
|---|---|
| 'Content-Type': 'application/json' | |
| 'Content-Type': 'application/x-www-form-urlencoded' | 指定提交方式是表单提交 |
-
body: 请求的 body 信息,可能是一个 Blob、BufferSource、FormData、URLSearchParams 或者 USVString 对象。(如果是 GET 或 HEAD 方法,则不能包含 body 信息)
-
mode: 请求的模式,主要用于跨域设置,如 cors、 no-cors 或者 same-origin。
| 参数 | 说明 |
|---|---|
| cors | 跨域 |
| no-cors | 不跨域 |
| same-origin | 同源 |
- credentials: 需要向服务器发送cookie时设置,如 omit、same-origin 或者 include。
| 参数 | 说明 |
|---|---|
omit默认 |
忽略的意思,也就是不带cookie |
| same-origin | 意思就是同源请求带cookie |
include |
表示无论跨域还是同源请求都会带cookie |
- cache: 请求的 cache 模式: default, no-store, reload, no-cache, force-cache, or only-if-cached。
如果遇到不会的,可以参考vuemao-csr上的fetch
// fetch post
fetch('url', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded' // 指定提交方式为表单提交
},
credentials: 'include', // 请求都带cookie
body: querystring.stringify(param)
}).then((res)=>{
return res.text()
}).then((res)=>{
console.log(res)
})
// fetch get
fetch('url', {
credentials: 'include', // 请求都带cookie
}).then((res) => {
return res.json()
}).then((res) => {
console.log(res)
})