之前写过一篇《ajax、axios、fetch之间的详细区别以及优缺点》 戳这里

1.封装 (http.js)

class Ajax {
get(url) {
return new Promise((resolve, reject) => {
fetch(url)
.then(res => res.json())
.then(data => resolve(data))
.catch(err => reject(err)) })
} // post方式
post(url, data) {
return new Promise((resolve, reject) => {
fetch(url, {
method: 'POST',
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify(data)
})
.then(res => res.json())
.then(data => resolve(data))
.catch(err => reject(err)) })
} //put 修改
put(url, data) {
return new Promise((resolve, reject) => {
fetch(url, {
method: 'PUT',
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify(data)
})
.then(res => res.json())
.then(data => resolve(data))
.catch(err => reject(err)) })
} //delete
delete(url, data) {
return new Promise((resolve, reject) => {
fetch(url, {
method: 'DELETE',
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify(data)
})
.then(res => res.json())
.then(data => resolve('数据删除成功!'))
.catch(err => reject(err))
})
}
}
export default new Ajax();//ES6导出

2.调用

import http from "./http.js"//引入方式 这里用的是ES6的方法,需要babel配合webpack打包
//普通引入使用src引入之后 const http = new Ajax(); 即可
// get请求数据
http.get('http://jsonplaceholder.typicode.com/users')
.then((data) => {
console.log(data)
})
.catch(err => console.log(err)) // post传输数据
const data = {
name: 'candy',
username: 'candy',
email: 'htmlcs@163.com'
};
//post user
http.post('http://jsonplaceholder.typicode.com/users', data)
.then(data => console.log(data))
.catch(err => console.log(err)) // update user ,修改后会发现修改后ID为2的数据会变成上页面定义的data
http.put('http://jsonplaceholder.typicode.com/users/2', data)
.then(data => console.log(data))
.catch(err => console.log(err)) //delete user 删除下标为2里的数据 http.delete('http://jsonplaceholder.typicode.com/users/2', data)
.then(data => console.log(data))
.catch(err => console.log(err))

这里有324.57GB的修仙资料。嘿嘿嘿你懂得。/手动狗头


那么问题来了,如果你也想入坑前端或者学习更多技术,广交天下朋友(基友),认识更多有趣的灵魂的话,欢迎加入前端交流群鸭~

扫二维码加为好友就完事了!安排~

最新文章

  1. js 对象合并
  2. EventAggregator, EventBus的实现
  3. SQLServer内核架构剖析 (转载)
  4. remove() 方法的兼容问题
  5. EXT学习之——Ext下拉框绑定无效的问题
  6. ssh ip "WARING:REMOTE HOST IDENTIFICATION HAS CHANGED!"
  7. Struts2+Spring3+Mybatis3开发环境搭建
  8. Windows USN Journal Parsing
  9. iOS block简单传值
  10. eclipse 将文件夹作为sourcefolder
  11. 税号输入框 将input框中的输入自动转化成半角大写
  12. Html标签,file方式,上传文件
  13. Gazebo與ROS版本說明
  14. [Swift]LeetCode48. 旋转图像 | Rotate Image
  15. Feature Extractor[ResNet v2]
  16. python 之路,Day 1 python基础 之 课后随笔
  17. hdu1811 拓扑排序+并查集缩点
  18. python 利用selectors实现异步I/O
  19. 理解git的分支原理,更好地使用git
  20. Activity服务类-9 TaskService服务类

热门文章

  1. 1041 Be Unique (20分)(水)
  2. Java反射(六)纯面向接口编程的简单框架实践
  3. python之excel的封装
  4. ps 命令显示不完整的问题
  5. 聊一聊深拷贝和浅拷贝(JS)
  6. AJ学IOS(47)之网易彩票帮助界面UIWebView的运用
  7. AJ学IOS(07)UI之UITextField代理事件_类似QQ登陆窗口的简单实现
  8. 编写高质量Python程序(三)基础语法
  9. Spring Cloud 系列之 Gateway 服务网关(二)
  10. Ubuntu安装Elasticsearch6.3