使用fetch代替传统的Ajax

来源:互联网 发布:淘宝店铺首页产品链接 编辑:程序博客网 时间:2024/06/11 06:21

在 jQuery 开发时代,jQuery 已经为我们封装了非常优雅的 ajax 函数,并且针对各个浏览器都做了很好的兼容,使用起来非常方便。但是,当我们使用React或Vue或Angular开发时,就没有必要为了使用Ajax而导入一整个jQuery。同时,JavaScript 中的 ajax 很早之前就有一个诟病————复杂业务下的 callback 嵌套的问题。为了解决这个问题,ES6的语法推出来Promise,fetch中也使用了Promise语法。

fetch就是一种可代替 ajax 获取/提交数据的技术,有些高级浏览器已经可以window.fetch使用了。相比于使用 jQuery.ajax 它轻量(只做这一件事),而且它原生支持 promise ,更加符合现在编程习惯。

封装fetch的get、post方法

import 'whatwg-fetch'import 'es6-promise'export function get(url) {  var result = fetch(url, {      credentials: 'include',      headers: {          'Accept': 'application/json, text/plain, */*'      }  });  return result;}
import 'whatwg-fetch'import 'es6-promise'// 将对象拼接成 key1=val1&key2=val2&key3=val3 的字符串形式function obj2params(obj) {    var result = '';    var item;    for (item in obj) {        result += '&' + item + '=' + encodeURIComponent(obj[item]);    }    if (result) {        result = result.slice(1);    }    return result;}// 发送 post 请求export function post(url, paramsObj) {    var result = fetch(url, {        method: 'POST',        credentials: 'include',        headers: {            'Accept': 'application/json, text/plain, */*',            'Content-Type': 'application/x-www-form-urlencoded'        },        body: obj2params(paramsObj)    });    return result;}
阅读全文
0 0
原创粉丝点击