跳转到主要内容

主页内容

下一代Ajax技术——Fetch API

由 webadmin 发布于 阅读 54 次

1、什么是Fetch?

  • (1)、Fetch被称之为下一代Ajax技术,内部采用promise方式来处理数据。
  • (2)、API语法简洁明了,比XMLHttpRequest更加简单易用。
  • (3)、采用了模块化设计,API分散于多个对象中(如:Response对象、Request对象、Header对象)。
  • (4)、通过数据流(Stream对象)处理数据,可以分块读取,有利于提高网站性能,对于大文件或者网速慢的场景极为有用。

2、兼容性

除了IE,其他的浏览器都兼容。

3、使用Fetch

3.1、使用fetch发送基本的get请求

如果fetch( 只接收了一个url字符串参数,表示默认向该网址发送get 请求,会返回一个Promise对象如果需要设置get的参数,直接拼接到 url 地址上即可。

语法:

fetch(url)
 .then()
 .catch()

基本的Get请求实例:不带任何参数。

fetch('/demo_ajax/ajax/test_fetch_ge').then(res => {
      //这里的res是一个Response对象,需要通过特定方法来获取其中的内容(后台返回的内容)
      console.log(res);
      //res.json()是一个异步操作,表示取出所有内容并转换成json对象
      return res.json();//这里返回的是Promise对象
    }).then(json => {
      //json是经过res.json()处理后的数据
      console.log(json);
    } ).catch(err => {
      //捕获错误信息
      console.log(err);
})

把代码封装成async异步函数:

async function test_fetch_get(){
    try{
      //先获取Response对象
      let res = await fetch('http://ajax-base-api-t.itheima.net/api/getbooks');
      //console.log(res);//拿到Response对象
      //通过res.json()获取其中的内容(后台返回的内容)
      return  await res.json();//返回一个Promise对象
    }catch (err) {
      //捕获错误信息
      console.log(err);
    }
}

调用:

test_fetch_get().then(json => {
  console.log(json);
});

带参数的Get请求实例:查询id为2的图书的信息。

在请求地址后面拼接参数:

https://www.apiurl.com/api/endpoint?key1=value1&key2=value2&...
例如:
http://ajax-base-api-t.itheima.net/api/getbooks?id=2
async function test_fetch_get(){
    try{
      //先获取Response对象
      let res = await fetch('http://ajax-base-api-t.itheima.net/api/getbooks?id=2');
      //console.log(res);//拿到Response对象
      //通过res.json()获取其中的内容(后台返回的内容)
      return  await res.json();
    }catch (err) {
      //捕获错误信息
      console.log(err);
    }
}

3.2、Response对象

fetch()请求成功以后,得到的是一个 Response 对象。它对应服务器的 HTTP 响应。

const response = await fetch(url);
//得到一个Response对象

3.2.1、Response对象常用属性

属性含义
Response.ok返回一个布尔值,表示请求是否成功,true对应 HTTP 请求的状态码 200 到 299,false对应其他的状态码。
Response.status返回一个数字,表示 HTTP 回应的状态码(例如200,表示成功请求)。
Response.statusText返回一个字符串,表示 HTTP 回应的状态信息(例如请求成功以后,服务器返回”OK”)。
Response.url返回请求的 URL。如果 URL 存在跳转,该属性返回的是最终 URL。
Response.type
  • basic:普通请求,即同源请求。
  • cors:跨域请求。
  • error:网络错误,主要用于 Service Worker。
  • opaque:如果fetch()请求的type属性设为no-cors,就会返回这个值,详见请求部分。表示发出的是简单的跨域请求,类似<form>表单的那种跨域请求。
  • opaqueredirect:如果fetch()请求的redirect属性设为manual,就会返回这个值,详见请求部分。
Response.redirected返回一个布尔值,表示请求是否发生过跳转。

3.2.2、Response对象常见的方法

方法作用
response.text()得到文本字符串。
response.json()得到 JSON 对象。
response.blob()得到二进制 Blob 对象。
response.formData()得到 FormData 表单对象。
response.arrayBuffer()得到二进制 ArrayBuffer 对象。

3.2.3、发送post请求

语法:

fetch(url,{
	method: '请求的方法(常见的有:POST、DELETE、PUT、PATCH)',
	headers:{
          'Content-Type': '请求格式'
          //常见的有:application/json;charset=utf-8
                    application/x-www-form-urlencoded
                    multipart/form-data
    },
    body: "请求体数据"
})

post请求实例:

async function test_fetch_post( params ){
    try{
      let res = await fetch('http://ajax-base-api-t.itheima.net/api/addbook',{
        method: 'POST',//请求方法:post
        headers:{
          'Content-Type': 'application/json'//数据格式为json
        },
        body: JSON.stringify(params)//序列化对象
      });
      return await res.json();
    }catch (err){
      console.warn(err);
    }
}

调用:

$('#add-book').click(function () {
    let book_info = {
      bookname: '金瓶梅',
      author: '兰陵笑笑生',
      publisher: '人民出版社'
    };
    test_fetch_post( book_info ).then(json=>{
      console.log(json);
    })
})

4、Fetch函数封装

4.1、封装需求

例如:

get、delete请求的参数需要请求url后面拼接。

put、patch、post请求的参数需要json设置请求头。

目标效果:

发送get、delete请求:

http({
	method: 'xxx',
	url: 'xxxxx',
	params: {......}
})

发送put、patch、post请求:

http({
	method: 'xxx',
	url: 'xxxxx',
	data: {......}
})

封装fetch函数:

//封装fetch函数
async function http( options ){
    //对象解构赋值
    let {method, url, params, data} = options;
    //1、如果有params参数:需要将params参数从对象转换成"key=value&key=value"的形式,并且拼接到url后面;如果没有,则不用管。
    if (params){
      //将params对象转换成"key=value&key=value"的形式
      //new URLSearchParams(params).toString()可以直接将对象转换成"key=value&key=value"的形式
      let paramsUrl = new URLSearchParams(params).toString();
      //将参数拼接到url后面
      url += '?' + paramsUrl;
    }
    let res; //最终结果
    //2、如果有data:需要写完整的headers...代码,如果没有则不需要设置headers
    if (data){
      //有data
      try {
        res = await fetch( url, {
          method,
          headers:{
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(data)
        } );
      }catch (err){
        throw new Error(err);
      }
    }else{
      try{
        //没有data
        res = await fetch( url );
      }catch (err){
        throw new Error(err);
      }
    }
    //把获取的结果经过处理返回出去
    return res.json();
}

将以上封装好的fetch函数抽离出来为一个http.js,在其他文件可以引入使用。

调用:发起get请求

$('#test1').click(function () {
     http({
        method: 'GET',
        url: 'http://ajax-base-api-t.itheima.net/api/getbooks',
        params: {
          id: 1
        }
      }).then(json => {
        console.log(json.msg);
     }).catch(err=>{
       console.log(err);
     })
})

 调用:发起post请求

$('#test2').click(function () {
    let book_info = {
      bookname: '屌丝如何逆袭222',
      author: '屌丝',
      publisher: '屌丝出版社'
    };
    http({
      method: 'POST',
      url: 'http://ajax-base-api-t.itheima.net/api/addbook',
      data: book_info
    }).then(json => {
      console.log(json.msg);
    }).catch(err=>{
      console.log(err);
    })
})