Ajax与Fetch

发布时间:2019-08-20 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Ajax与Fetch脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

介绍

页面中需要向服务器请求数据时,基本上都会使用Ajax来实现。Ajax的本质是使用XMLHttPRequest对象来请求数据。XMLHttpRequest的使用如下:

VAR xhr = new XMLHttpRequest();
xhr.oPEn('GET', url, true);
xhr.onload = function() {
  console.LOG(xhr.response);
};
xhr.onerror = function() {
  console.error('error');
};
xhr.send();

可以看出,XMLHttpRequest对象是通过事件的模式来实现返回数据的处理的。目前还有一个是采用Promise方式来处理数据的,这个技叫做Fetch。

Fetch的使用

使用Fetch实现请求的最基本代码:

fetch(url).then(function (response) {
  return response.json();  // json返回数据
}).then(function (data) {
  console.log(data);  // 业务逻辑
}).catch(function (e) {
  console.error('error');
})

使用ES6的箭头函数后,可以更加简洁:

fetch(url).then(response => response.json())
.then(data => console.log(data))
.catch(e => console.error('error'));

还可以使用es7的async/await进一步简化代码:

try {
  let response = await fetch(url);
  let data = response.json();
  console.log(data);
} catch(e) {
  console.log('error');
}

这样,异步的请求可以按照同步的写法来写了。

Fetch修改head信息

fetch方法中还有第二个参数,第二个参数是用于修改请求的Head信息的。可以在里面指定method是GET还是POST;如果是跨域的话,可以指定mode为cors来解决跨域问题。

var headers = new Headers({
  "Origin": "http://taobao.COM"
});
headers.append("Content-Type", "text/plain");

var init = {
  method: 'GET',
  headers: headers,
  mode: 'cors',
  cache: 'default'
};

fetch(url, init).then(response => response.json())
.then(data => console.log(data))
.catch(e => console.error('error'));

脚本宝典总结

以上是脚本宝典为你收集整理的Ajax与Fetch全部内容,希望文章能够帮你解决Ajax与Fetch所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。