使用fetch代替传统的Ajax

前端之家收集整理的这篇文章主要介绍了使用fetch代替传统的Ajax前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

在 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,*/*','Content-Type': 'application/x-www-form-urlencoded'
        },body: obj2params(paramsObj)
    });

    return result;
}
原文链接:https://www.f2er.com/ajax/160640.html

猜你在找的Ajax相关文章