Ajax新玩法fetch API

来源:互联网 发布:java aes算法 编辑:程序博客网 时间:2024/05/21 08:31

目前 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是什么?

 

原创粉丝点击