目录

  • 前言
  • 一、fetch
    • 1、基本特性
    • 2、语法
    • 3、基本用法
  • 二、fetch请求参数
    • 1、常用的配置项
    • 2、get请求传参
    • 3、post请求传参
  • 三、fetch响应结果
    • 响应数据格式

前言

fetch是基于Promise来实现的,Promise用法:Promise用法及基于Promise处理ajax请求

一、fetch

1、基本特性

更加简单的数据获取方式,功能更强大,更灵活,可以看作是xhr的升级版

官方:https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

xhr相关知识点:

2、语法

fetch(url).then(fn2)
		  .then(fn3)
		  ...
		  .catch(fn)

3、基本用法

text()方法属于fetchAPI的一部分,它返回一个Promise实例对象,需要return
用途:用于获取后台返回的数据

fetch('/abc').then(data =>{
	return data.text(); // text()返回的是一个Promise对象
}).then(ret =>{
	//这里得到的才是最终的数据
	console.log(ret)
});

二、fetch请求参数

1、常用的配置项

配置项 类型 说明
method String HTTP请求方法,默认为get(get、post、put、delete)
body String HTTP请求参数
headers Object HTTP请求头,默认为{}

2、get请求传参

put类似

fetch('/abc?id=123',{
	method:'get'
}).then(data=>{
        return data.text()
}).then(ret=>{
        // 这里得到的才是真正的数据
        console.log(ret);
   })

3、post请求传参

delete类似
必须写请求头

fetch("/abc", {
  method: "POST",
  body: "uname=list&pwd=123",
  headers:{
  	'Content-Type','application/x-www-form-urlencoded';
  }
})
  .then((data) => {
    return data.text();
  })
  .then((ret) => {
    // 这里得到的才是真正的数据
    console.log(ret);
  });

三、fetch响应结果

响应数据格式

名称 说明
text() 将返回体处理成字符串类型
json() 返回结果和JSON.parse(responseText)一样
fetch("/abc/json")
    .then((data) => {
      // return data.text();
      return data.json()
    })
    .then((ret) => {
      // 这里得到的才是真正的数据
      console.log(ret);
    });
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。