zoukankan      html  css  js  c++  java
  • Ajax新玩法fetch API

    目前 Web 异步应用都是基于 XMLHttpRequest/ActiveXObject (IE)实现的, 这些对象不是专门为资源获取而设计的,因而它们的 API 非常复杂,同时还需要开发者处理兼容性问题。 虽然开发者普遍使用 $.ajax() 这样的上层包装,但 Fetch API 意在提供更加方便和一致的原生 API, 同时统一 Web 平台上的资源获取行为,包括外链脚本、样式、图片、AJAX 等。同时Fetch API使用Promise,因此是一种简洁明了的API,比XMLHttpRequest更加简单易用。

    fetch API 语法

     1  fetch(url)
     2     .then(function(response) {
     3         return response.json();
     4     })
     5     .then(function(data) {
     6         console.log(data);
     7     })
     8     .catch(function(e) {
     9         console.log("Oops, error");
    10     });
    11 //使用 ES6 的 箭头函数
    12  fetch(url)
    13     .then(response => response.json())
    14     .then(data => console.log(data))
    15     .catch(e => console.log("Oops, error", e))
    16 //使用 async/await 来做最终优化
    17 //使用 await 后,写异步代码就像写同步代码一样爽。await 后面可以跟 Promise 对象,表示等待 Promise resolve() 才会继续向下执行,如果 Promise 被 reject() 或抛出异常则会被外面的 try…catch 捕获。
    18   (async function () {
    19     try {
    20         let response = await fetch(url);
    21         let data = response.json();
    22         console.log(data);
    23     } catch(e) {
    24         console.log("Oops, error", e);
    25     }
    26 })();

     GET请求

    1   fetch(url, {
    2     method: "GET", //默认
    3     headers:{
    4         "Accept": "application/json, text/plain, */*"
    5     }
    6 })
    7 .then(response => response.json())
    8 .then(data => console.log(data))
    9 .catch(e => console.log("Oops, error", e))

    POST请求

     fetch(url, {
        method: "POST",
        headers: {
            "Accept": "application/json, text/plain, */*",
            "Content-type":"application:/x-www-form-urlencoded; charset=UTF-8"
        },
        body: "name=hzzly&age=22"
    })
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(e => console.log("Oops, error", e))

    使用Fetch请求发送凭证

    要使用Fetch发送带有诸如cookie之类的凭证的请求。你可以在选项对象中将credentials属性值设置为“include”:

      fetch(url,{
        credentials: "include"
    })

    封装POST请求

      //将对象拼接成 name=hzzly&age=22 的字符串形式
    function params(obj) {
        let result = ''
        for(let item in obj) {
            result += `&${item}=${obj[item]}`
        }
        if(result) {
            result = result.slice(1)
        }
        return result
    }
    
    function post(url, paramsObj) {
        let result = fetch(url, {
            methods: 'POST',
            credentials: "include"
            headers: {
                "Accept": "application/json, text/plain, */*",
                "Content-type":"application:/x-www-form-urlencoded; charset=UTF-8"
            },
            body: params(paramsObj)
        })
        return result
    }
    
    let obj = {
        name: 'hzzly',
        age: 22
    }
    post(url, obj)
        .then(response => response.json())
        .then(data => console.log(data))
        .catch(e => console.log("Oops, error", e))

    原文 请点击这里React 标配的Fetch是什么?

  • 相关阅读:
    Maven部署构件至远程仓库
    Maven远程仓库的认证
    Maven远程仓库的配置
    Maven实战系列文章
    使用Maven私服的好处
    使用Mavne生成可以执行的jar文件
    Visual Studio for Mac 简介
    HTTP 2.0与HTTP 1.1区别
    使用Microsoft的IoC框架:Unity来对.NET应用进行解耦
    围绕央行系统升级所产生的常见问题
  • 原文地址:https://www.cnblogs.com/leungUwah/p/7077065.html
Copyright © 2011-2022 走看看