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是什么?
阅读全文
0 0
- Ajax新玩法fetch API
- Fetch-新一代Ajax API
- fetch简介: 新一代Ajax API
- 这个API很“迷人”——(新的Fetch API)
- Fetch API
- fetch API
- Fetch API
- fetch api
- 街机游戏新玩法
- 墨迹天气新玩法
- 淘宝新玩法
- JavaEE 新玩法
- Xcode8一些新玩法
- 游戏新玩法之恋人玩法
- 新的Google Ajax Search Api
- 新的Google Ajax Search Api
- 新的Google Ajax Search Api
- 新的Google Ajax Search Api
- Python3:《机器学习实战》之k近邻算法(1)算法概述
- java中移位运算符<< >>
- 【转载】二叉树的非递归遍历
- NOIP 模拟题 可接受序列
- Android 3D旋转动画库
- Ajax新玩法fetch API
- php中的引用变量1
- Mongo查询操作
- hdu记录状态bfs
- CSS vertical-align 属性
- 信用不好贷款总被拒?五招教你提信用!
- SSM框架搭建,有程序,附带所需jar包
- 阿里云数据库掌门人褚霸:骑行与数据人生
- 使用jmail发送邮件