js fetch

ajax请求数据可以使用新的方法 Fetch

Fetch返回一个promise对象  参考资料 http://www.ruanyifeng.com/blog/2015/05/async.html

必须先了解promise对象,否则无法使用fetch,因为看不懂

但看了还是不能明白这个promise对象. 

如何实现用Fetch做ajax请求

fetch有包装库 <script src="https://cdn.bootcss.com/fetch/2.0.4/fetch.min.js"></script>

fetch接口API手册地址  https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch

// 1.请求参数,可以使用formdata

let formData = new FormData();

formData.append(key1,val1);

// 2.配置请求,发送并处理结果

fetch(

  // 第一个参数,接口地址

  url, 

  // 第二个参数是一个对象,配置请求信息,如get post,是否跨域,headers内容等,请求参数等

  {

    // GET, POST, PUT, DELETE,
    method: "POST", 

     // 跨域cros  no-cors, cors, *same-origin

    mode: 'cors',

    // headers信息

    headers:

    {
      "accessToken": token
    },

    // 请求参数
    body: formData
  }

)

// fetch方法返回一个promise对象,这里使用连写

// 第1个then里面,使用这句话,返回请求结果 

.then(response => response.json())

// 第2个then里面,函数参数json就是第1个then返回的请求结果

.then(function (json)
{

// 请求结果处理...

}

// catch函数处理请求时发生的异常.比如服务器错误之类的

.catch(function (err)
{
  alert(err);
});

总结起来方法分三块.

1.发送请求,2.返回结果,3.处理结果(处理异常)

fetch(url,{})

.then(return rejson)

.then(process rejson)

.catch(process catch)

优缺

在形式上和AJAX请求差不多,也是配置请求参数,使用回调函数处理结果.

在回调函数嵌套层数不多时,并不感觉方便.

使用.then可以较直观的处理回调函数,处理上一个then函数的结果,作用和回调函数相同.并且可以并排写多个.then

fetch(url,{})

.then(return json)

.then(return callback1(json))

.then(return callback2(c1rejson))

.then(return callback3(c2rejson))

遗憾的是未能完全理解promise,依然觉得麻烦与复杂 

猜你喜欢

转载自www.cnblogs.com/mirrortom/p/9298970.html